The little buddy with Hibernate knows that both the annotation and the object-relational mapping file will associate the attributes of the entity class with the columns of the data table. For example, student has a Student.hbm.xml file, the Object relational mapping file has ID also has the property and other tags. This allows for a good table and entity association.
MyBatis also need to be associated with tables and entities. We are querying the table, and the returned result is the entity class. There is a correspondence between the two.
If the attribute of the entity class corresponds to the column name one by one of the table, the name is the same, which automatically solves the problem. But if the attribute of the entity class is inconsistent with the column name of the table, then we need to associate them manually.
We check the official document, can see such a configuration: whether to open the hump naming rules, this later.
Create a data table first
CREATE TABLE book ( intnull auto_increment COMMENT ' books ID ', book_name varchar ( null COMMENT ' book name ', primary KEY (book_id)) ENGINE=innodb auto_increment=3 DEFAULT charset= UTF8 COMMENT ' books ';
Insert into book (Book_name) VALUES (' Song of Ice and Fire ');
Create another entity class book, here I deliberately make the entity Class property and table column name inconsistent
Packagecom.zhao.entity; Public classBook {Private intID; PrivateString BookName; Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString Getbookname () {returnBookName; } Public voidsetbookname (String bookname) { This. BookName =BookName; } @Override PublicString toString () {return"Book [id=" + ID + ", bookname=" + BookName + "]"; }}
can now see table book column book_id book_name; Entity class book Property ID bookname.
I still use the combination of XML and DAO interfaces for data table operations
Package Com.zhao.dao; Import Com.zhao.entity.Book; Public Interface Bookdao { / * * Insert book information */public int insertbook (book book); /* * Query book information by ID */public book querybyid (int ID);}
In the interface we define two methods, one to insert a query.
Next look at Bookdao.xml.
<?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 "><Mappernamespace= "Com.zhao.dao.BookDao"> <InsertID= "Insertbook"ParameterType= "book">INSERT into book (Book_name) VALUES (#{bookname})</Insert> <SelectID= "Querybyid"resulttype= "book">SELECT * from book where Book_id=#{id}</Select></Mapper>
Now for a brief test
PackageCom.zhao.dao;Importjava.io.IOException;ImportJava.io.Reader;Importorg.apache.ibatis.io.Resources;Importorg.apache.ibatis.session.SqlSession;Importorg.apache.ibatis.session.SqlSessionFactory;ImportOrg.apache.ibatis.session.SqlSessionFactoryBuilder;ImportOrg.junit.After;ImportOrg.junit.Before;Importorg.junit.Test;ImportCom.zhao.entity.Book; Public classBookdaotest {PrivateString resource = "Mybatis-config.xml"; PrivateReader Reader; Privatesqlsessionfactory sqlsessionfactory; Privatesqlsession sqlsession; PrivateBookdao Bookdao; @Before Public voidBefore ()throwsIOException {Reader=Resources.getresourceasreader (Resource); Sqlsessionfactory=NewSqlsessionfactorybuilder (). build (reader); Sqlsession=sqlsessionfactory.opensession (); Bookdao= (Bookdao) sqlsession.getmapper (Bookdao.class); } @After Public voidAfter () {sqlsession.close (); } @Test Public voidTestinsertbook () { Book Book=NewBook (); Book.setbookname ("Song of Ice and Fire"); intInsertcount=Bookdao.insertbook (book); //Be sure to remember to commit the transactionSqlsession.commit (); System.out.println ("Insertcount:" +insertcount); } @Test Public voidTestquerybyid () { Book Book=bookdao.querybyid (3); SYSTEM.OUT.PRINTLN (book); }}
Test results
The idea is particularly simple, which is to assign the results from the data table book to the book object. The program runs without error and the result is incorrect just because the data table and entity class are not associated. In fact, we have found out the data from the table, but we have failed to assign the book this step.
Workaround:
1: Define aliases for columns in the data table
Modify Bookdao.xml
<id= "Querybyid" resulttype= "book"> Select book_id as ID, book_name as bookname from book where Book_id=#{id} </Select C14>>
The previous SELECT * was modified to add an alias to the result. This alias corresponds to the properties of the book.
View Results
2:resultmap Manually Configuring associations
Our goal is still to associate the columns of the table with the attributes of the entity class, which also mentions the object-relational mapping of hibernate, in fact MyBatis configuration Resultmap and Hibernate object-relational mappings are very similar.
Modify Bookdao.xml
<SelectID= "Querybyid"Resultmap= "Bookresultmap">SELECT * from book where Book_id=#{id}</Select> <Resultmaptype= "book"ID= "Bookresultmap"> <ID Property= "id"column= "book_id"/> <result Property= "BookName"column= "Book_name"/> </Resultmap>
Only SELECT * Must be a failure. But we can configure the one by one correspondence between the attributes of the entity class and the columns of the data table.
Query results
3: Using the above two methods, I think it is a bit cumbersome. There's no simpler way, there is.
Use the above mentioned whether to open the hump rule.
In general, the columns of a database table are defined in a_column format, whereas the attributes of an entity class are defined in acolumn format. It's like it's used up there.
Book_name and BookName.
These two days I tidied up the XML and DAO layer combinations using the MyBatis operation, and did not use the definition alias or define Resultmap as described above. Instead, the rules for opening the hump are used.
In the Mybatis-config.xml
< Settings > < name= "Mapunderscoretocamelcase" value= "true"/> <name= "Usegeneratedkeys" value= "true" /> </settings>
Of course, when designing tables and creating entity classes, pay attention to the correspondence between Book_name and BookName.
In fact, the essence of opening the hump rule is to define an alias for the table. But this kind of alias is normative, Book_name's alias says BookName.
MyBatis Tables and entity associations