Share to: share facebook share twitter share wa share telegram print page

MyBatis

MyBatis
Developer(s)The MyBatis team
Stable release
3.5.16[1] Edit this on Wikidata / 4 April 2024
Repository
Written inJava
Operating systemCross-platform
TypePersistence framework
LicenseApache License 2.0
Websitewww.mybatis.org Edit this on Wikidata

MyBatis is a Java persistence framework that couples objects with stored procedures or SQL statements using an XML descriptor or annotations.

MyBatis is free software that is distributed under the Apache License 2.0.

MyBatis is a fork of iBATIS 3.0 and is maintained by a team that includes the original creators of iBATIS.

Feature summary

Unlike ORM frameworks, MyBatis does not map Java objects to database tables but Java methods to SQL statements.

MyBatis lets you use all your database functionality like stored procedures, views, queries of any complexity and vendor proprietary features. It is often a good choice for legacy or de-normalized databases or to obtain full control of SQL execution.

It simplifies coding compared to JDBC. SQL statements are executed with a single line.

MyBatis provides a mapping engine that maps SQL results to object trees in a declarative way.

SQL statements can be built dynamically by using a built-in language with XML-like syntax or with Apache Velocity using the Velocity integration plugin.

MyBatis integrates with Spring Framework and Google Guice. This feature allows one to build business code free of dependencies.

MyBatis supports declarative data caching. A statement can be marked as cacheable so any data retrieved from the database will be stored in a cache and future executions of that statement will retrieve the cached data instead hitting the database. MyBatis provides a default cache implementation based on a Java HashMap and default connectors for integrating with: OSCache, Ehcache, Hazelcast and Memcached. It provides an API to plug other cache implementations.

Usage

SQL statements are stored in XML files or annotations. Below depicts a MyBatis mapper, that consists of a Java interface with some MyBatis annotations:

package org.mybatis.example;

public interface BlogMapper {
    @Select("select * from Blog where id = #{id}")
    Blog selectBlog(int id);
}

The sentence is executed as follows.

BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);

SQL statements and mappings can also be externalized to an XML file as follows.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
    <select id="selectBlog" parameterType="int" resultType="Blog">
        select * from Blog where id = #{id}
    </select>
</mapper>

Statements can also be executed using the MyBatis API.

Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);

For details, please refer to the User Guide available at MyBatis site. See external links.

Spring integration

MyBatis integrates with Spring Framework. This module allows MyBatis to participate in Spring transactions. It will also build MyBatis mappers and sessions and inject them into other beans.

The following sample shows a basic XML configuration that sets up a mapper and injects it into a "BlogService" bean.

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="blogMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    <property name="mapperInterface" value="org.mybatis.example.BlogMapper" />
</bean>

<bean id="blogService" class="org.mybatis.example.BlogServiceImpl">
    <property name="blogMapper" ref="blogMapper" />
</bean>

Calling MyBatis is now just calling a bean:

public class BlogServiceImpl implements BlogService {

    private BlogMapper blogMapper;

    public void setBlogMapper(BlogMapper blogMapper) {
        this.blogMapper = blogMapper;
    }

    public void doSomethingWithABlog(int blogId) {
        Blog blog = blogMapper.selectBlog(blogId);
        ...
    }
}

Velocity language

The Velocity language driver lets you use Apache Velocity to generate your dynamic SQL queries on the fly.

<select id="findPerson" lang="velocity">
  #set( $pattern = $_parameter.name + '%' )
  SELECT *
  FROM person
  WHERE name LIKE @{pattern, jdbcType=VARCHAR}
</select>

MyBatis Generator

MyBatis provides a code generator. MyBatis Generator will introspect a database table (or many tables) and generate MyBatis artifacts needed to perform CRUD operations (Create, Retrieve, Update, Delete).

An Eclipse plugin is available.

It will preserve any custom code in case of regeneration but only if you use the Eclipse plugin.

MyBatis Migrations

MyBatis Migrations is a Java command line tool that keeps track of database schema changes managing DDL files (known as migrations).

Migrations allows to query the current status of the database, apply schema changes and also undo them. It also helps to detect and solve concurrent database schema changes made by different developers.

History

MyBatis project is a subsidiary of iBATIS 3.0 and maintained by a team which includes the original creators of iBATIS.

The project was created on May 19, 2010 when Apache iBATIS 3.0 was published and the team announced that the development will continue under a new name and a new home at Google Code.[2]

[3]

See also

References

  1. ^ "Release 3.5.15". 4 April 2024. Retrieved 9 July 2024.
  2. ^ iBATIS Project Team Moving to Google Code
  3. ^ Bye Google Code welcome Github

Read other articles:

Public park in Turkey AltınparkA view of Altınpark (1997)AltınparkLocationAltındağ, Ankara, TurkeyCoordinates39°35′N 32°32′E / 39.58°N 32.53°E / 39.58; 32.53Area64 ha (160 acres)Created1985; 39 years ago (1985)WebsiteANFA, the management Altınpark (literally Golden Park) is a public park in Ankara, Turkey Geography Altınpark is in Altındağ district of Ankara, situated on the way connecting Ankara to Ankara airport. The park area is …

Artikel ini sebatang kara, artinya tidak ada artikel lain yang memiliki pranala balik ke halaman ini.Bantulah menambah pranala ke artikel ini dari artikel yang berhubungan atau coba peralatan pencari pranala.Tag ini diberikan pada Februari 2023. Alosterna perpera Klasifikasi ilmiah Kerajaan: Animalia Filum: Arthropoda Kelas: Insecta Ordo: Coleoptera Famili: Cerambycidae Genus: Alosterna Spesies: Alosterna perpera Alosterna perpera adalah spesies kumbang tanduk panjang yang tergolong famili Ceram…

Beberapa tokoh protagonis dari seri Fairy Tail. Searah jarum jam dari kiri atas: Elfman Strauss, Plue, Makarov Dreyar, Lucy Heartfilia, Happy, Natsu Dragneel, Cana Alberona, Loke, Gray Fullbuster dan Mirajane Strauss Seri manga dan anime Fairy Tail menampilkan berbagai karakter yang diciptakan oleh Hiro Mashima. Seri ini sebagian besar berlatar di Kerajaan Fiore, sebuah negeri di dunia fiksi Earth-land, di mana sebagian penduduknya mampu melakukan berbagai jenis sihir. Mereka yang melakukan sihi…

Gatot Hariyanto Kapoksahli Koarmada RI ke-4PetahanaMulai menjabat 2 Oktober 2023 PendahuluDiki AtrianaPenggantiPetahana Informasi pribadiLahir20 Mei 1969 (umur 54)IndonesiaAlma materAkademi Angkatan Laut (1991)Karier militerPihak IndonesiaDinas/cabang TNI Angkatan LautMasa dinas1991—sekarangPangkat Laksamana Pertama TNINRP10134/PSatuanKorps SuplaiSunting kotak info • L • B Laksamana Pertama TNI Gatot Hariyanto (lahir 20 Mei 1969) adalah seorang perwira ting…

Tampak depan Rumah Si Pitung atau sering disebut Rumah Tinggi di Kelurahan Marunda Jakarta Utara. Rumah Si Pitung merupakan rumah adat panggung khas Betawi di wilayah pesisir. Rumah panggung Betawi di Kampung Marunda Pulo Jakarta Utara, salah satu rumah di Betawi Pesisir yang masih tersisa. Bangunannya tidak terawat karena sudah ditinggalkan penghuninya. Rumah panggung adalah salah satu jenis rumah tradisional suku Betawi yang lantainya ditinggikan dari tanah dengan menggunakan tiang-tiang kayu.…

Strada statale 309 dirRomeaLocalizzazioneStato Italia Regioni Emilia-Romagna DatiClassificazioneStrada statale InizioSS 309 presso Ravenna FineA14 dir presso Ravenna Lunghezza5,200[1] km GestoreANAS PercorsoStrade europee Manuale La strada statale 309 dir Romea (SS 309 dir) è una strada statale italiana, diramazione della strada statale 309 Romea. Indice 1 Percorso 1.1 Tabella percorso 2 Note 3 Voci correlate 4 Altri progetti Percorso Si tratta del proseguimento in direzione s…

Sidney Govou Govou pada 2018Informasi pribadiNama lengkap Sidney Rodrigue Noukpo Govou[1]Tanggal lahir 27 Juli 1979 (umur 44)Tempat lahir Le Puy-en-Velay, PrancisTinggi 1,75 m (5 ft 9 in)Posisi bermain Penyerang / Penyerang SayapKarier junior1992–1996 Brives-Charensac1996–1997 CO Le Puy1997–2000 LyonKarier senior*Tahun Tim Tampil (Gol)2000–2010 Lyon 292 (49)2010–2011 Panathinaikos 24 (3)2011–2013 Évian 36 (1)2013–2014 Lyon B 2 (0)2014–2015 Monts d'Or …

Ikan bakarIkan gurame bakar disajikan dengan sambal kecapSajianUtamaTempat asalIndonesia dan MalaysiaDaerahAsia TenggaraDibuat olehuniversalSuhu penyajianPanasBahan utamaikan, dibumbui dengan bawang putih, bawang merah dan bumbu lainnya, dipanggang di atas bara apiSunting kotak info • L • BBantuan penggunaan templat ini  Media: Ikan bakar Ikan bakar adalah hidangan ikan yang dibakar atau dipanggang di atas api atau bara api. Hidangan ikan yang dibakar, muncul secara univer…

Romanian football club This article is about the currently active association football club. For the dissolved club, see CS Dunărea Turris Turnu Măgurele. Football clubTurris Turnu MăgureleFull nameFotbal Club Turris-OltulTurnu MăgureleNickname(s)Turnenii(The People from Turnu Măgurele)Short nameTurrisFounded1965as Voința SaeleleDissolved2021GroundMunicipalCapacity2,000 Home colours Away colours AFC Turris-Oltul Turnu Măgurele, commonly known as Turris Turnu Măgurele, or simply Turris, w…

بابوا غينيا الجديدة فيالألعاب الأولمبيةالرمزPNGاللجنةPapua New Guinea Olympic Committeeالموقعwww.pngolympic.orgالميداليات ذهبية 0 فضية 0 برونزية 0 المجموع 0 ظهور صيفي197619801984198819921996200020042008201220162020شاركت بابوا غينيا الجديدة لأول مرة في الألعاب الأولمبية في دورة 1976 الصيفية، وأرسلت رياضيين للتنافس في كل …

Multi-purpose convention centerQuezon Convention CenterQCCfaçade of the convention centerQuezon Convention CenterLocation within LuzonShow map of LuzonQuezon Convention CenterQuezon Convention Center (Philippines)Show map of PhilippinesLocationLucena, Quezon, PhilippinesCoordinates13°55′42″N 121°36′50″E / 13.92833°N 121.61379°E / 13.92833; 121.61379Capacity7000Opened2001TenantsPhilippine Basketball Association (2006–present)Maharlika Pilipinas Basketball Le…

Kereta Api Airport Railink Service (ARS) YIAYAKA Bandara Internasional Yogyakarta setelah melewati spot kereta Jembatan MbelingInformasi umumJenis layananKereta api bandaraStatusBeroperasiDaerah operasiDaerah Operasi VI YogyakartaPendahuluKereta api Solo Ekspres (rangkaian)Mulai beroperasi6 Mei 2019Operator saat iniKAI BandaraLintas pelayananStasiun awalYogyakartaJumlah pemberhentian3 (termasuk terminus stasiun)Stasiun akhirBandara YIAJarak tempuh40 kmWaktu tempuh rerata39 menitFrekuensi perjala…

Japanese electronics and former optical disc manufacturer Taiyo Yuden Co., Ltd.太陽誘電株式会社Company typePublic (K.K)Traded asTYO: 6976Nikkei 225 ComponentIndustryElectronicsFoundedTokyo, Japan (March 23, 1950; 74 years ago (1950-03-23))FounderHikohachi SatoHeadquarters2-7-19, Kyobashi, Chuo-ku, Tokyo 104-0031, JapanKey peopleShoichi Tosaka, (CEO and President)ProductsCeramic capacitorsInductorsCircuit modules (for power supply, high frequency products)Recordable opti…

Unión Balompédica ConquenseCalcio Segni distintivi Uniformi di gara Casa Trasferta Colori sociali Bianco, nero Dati societari Città Cuenca Nazione  Spagna Confederazione UEFA Federazione FEF Fondazione 1946 Presidente Carlos Lacort Allenatore Eloy Jiménez Stadio Stadio La Fuensanta(3.500 posti) Sito web www.ubconquense.es Palmarès Si invita a seguire il modello di voce L'Unión Balompédica Conquense è una società calcistica con sede a Cuenca, in Castiglia-La Mancia, in Spagna. Gioca…

Comic book series This article is about the Dark Horse comic book series. For the DC Comics character, see Mask (DC Comics). This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: The Mask comics – news · newspapers · books · scholar · JSTOR (March 2024) (Learn how and when to remove this message) Comics characte…

Artikel ini bukan mengenai Costco; Cosco (India) Limited; Cusco (disambiguasi); atau Cosco, anak usaha regional dari Dorel Industries. China Ocean Shipping Company, LimitedKantor pusat COSCO di BeijingSebelumnyaChina Ocean Shipping (Group) CorporationJenisAnak perusahaanIndustriTransportasiNasibMenjadi anak usahaPenerusChina COSCO ShippingDidirikan27 April 1961; 63 tahun lalu (1961-04-27)Ditutup2016KantorpusatDistrik Xicheng, Beijing, TiongkokWilayah operasiSeluruh duniaJasaEkspedisi muatan…

American television series (1986–1990) For the stage show, see The Pee-wee Herman Show. Pee-wee's PlayhouseGenreChildren's television seriesNonsensical comedyCreated byPaul ReubensPresented byPee-wee HermanStarring Paul Reubens Laurence Fishburne Lynne Marie Stewart Phil Hartman S. Epatha Merkerson John Paragon Theme music composer George McGrath Mark Mothersbaugh Paul Reubens Opening themeMark MothersbaughEnding themeMark MothersbaughComposers Mark Mothersbaugh The Residents (2.1, 2.9, 3.2) D…

Si ce bandeau n'est plus pertinent, retirez-le. Cliquez ici pour en savoir plus. Certaines informations figurant dans cet article ou cette section devraient être mieux reliées aux sources mentionnées dans les sections « Bibliographie », « Sources » ou « Liens externes » (Juillet 2016). Vous pouvez améliorer la vérifiabilité en associant ces informations à des références à l'aide d'appels de notes. Marcel Sembat Marcel Sembat par Henri Manuel, vers 19…

Pakuwon Mall Solo BaruPakuwon Mall Solo Baru saat masih bernama Hartono Lifestyle Mall (2013)AlamatJl. Ir. Soekarno, Madegondo, Grogol, SukoharjoTanggal dibuka19 Oktober 2012PengurusPT Pakuwon Jati Tbk.PemilikPakuwon GroupJumlah lantai6Akses transportasi umum K6S  Pakuwon Mall Solo Baru, sebelumnya bernama Hartono Lifestyle Mall (bahasa Jawa: Hanacaraka, ꦲꦂꦠꦺꦴꦤꦺꦴ​ꦭꦶꦥ꦳ꦼꦱ꧀ꦠꦾ​ꦩꦭ꧀ꦭ꧀), adalah salah satu pusat perbelanjaan yang terletak di Kabu…

Pliers with a narrow, pointed tip Needle-nose pliers, also known as long-nose pliers and snipe-nose pliers, are both cutting and holding pliers used by artisans, jewellery designers, electricians, network engineers and other tradesmen to bend, re-position and snip wire. Their namesake long nose gives excellent control while the cutting edge near the pliers' joint provides one-tool convenience. Because of their long shape they are useful for reaching into small areas where cables or other materia…

Kembali kehalaman sebelumnya