Objective
Feel the progress of learning is still relatively slow ah, a full day of learning efficiency is not very high, a will watch TV, a tea, the requirements of their not strict ... Today, talk about the insertion of associated table data and the use of aliases.
Body
1. Associative insertion
Before, I had created a users table in my database, and now I have a new cell phone table cellphone, which is used to record information about a user's phone, as shown in the following structure:
Where cellphone corresponds to the entity class is:
Packageorg.tonny.entity; Public classcellphone{Private intID; Private intuserId; PrivateString number; PrivateString City; Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } Public intgetUserId () {returnuserId; } Public voidSetuserid (intuserId) { This. UserId =userId; } PublicString GetNumber () {returnNumber ; } Public voidSetnumber (String number) { This. Number =Number ; } PublicString getcity () {returnCity ; } Public voidsetcity (String city) { This. City =City ; } @Override PublicString toString () {return"Cellphone [id=" + ID + ", userid=" + UserId + ", number=" + number + ", city=" + City + "]"; } }
The field user_id in cellphone is a foreign key that corresponds to the primary key ID of the users table. Now I need to insert the user information, and also include his mobile phone information how to do it? The idea is to insert records into the users table before inserting related records into cellphone, but how user_id gets into a puzzle. The same mybatis provides us with a solution that is implemented through a configuration file with the following configuration information:
<InsertID= "Adduserbeforecellphone"ParameterType= "Org.tonny.entity.User"> <!--use the Selectkey tag to return Keyproperty to the primary key: Accept the property that returns the primary key, this example corresponds to the id attribute of the Entity class user Order:insert the time when the statement generated the primary key, MySQL after the operation (that is, after) , Oracle is Resulttype: The data type of the ID property returned to the entity class user before executing the SQL statement: SQL statement that generates the primary key value: SELECT last_insert_id () - <SelectkeyKeyproperty= "id"Order= "after"Resulttype= "Java.lang.Integer">SELECT last_insert_id ()</Selectkey>INSERT into Users (name,age) VALUES (#{name},#{age})</Insert> <InsertID= "Addcellphone4user"ParameterType= "Org.tonny.entity.Cellphone">INSERT into cellphone (user_id, number, city) VALUES (#{userid},#{number},#{city})</Insert>
When I added the user, I used the selectkey tag, which was used to return data to the primary key value returned by users, and its sub-label content was more detailed, not to repeat. Similarly, I added the statement to add cellphone. Then there is the Java test code:
Public voidAdduserandcellphone () {sqlsession sqlsession=sqlsessionfactory.opensession (); //Insert User TableString sql = "Org.tonny.mapper.UsersMapper.addUserBeforeCellphone";//identity string for mapping SQLUser User =NewUser (); User.setname ("Jerry Chien."); User.setage (-2); intresult =sqlsession.insert (SQL, user); System.out.println ("Insert User Execution Result:" +result); //Insert Phone numberCellphone Cellphone =NewCellphone (); Cellphone.setuserid (User.getid ()); Cellphone.setnumber ("18915892672"); Cellphone.setcity ("NJ"); SQL= "Org.tonny.mapper.UsersMapper.addCellphone4User"; Result=sqlsession.insert (SQL, cellphone); System.out.println ("Insert cellphone execution Result:" +result); Sqlsession.commit (); Sqlsession.close (); }
is to insert the users table first, execute int result = Sqlsession.insert (sql, user), and MyBatis will assign a value to the user ID, which can be taken out by User.getid (). Then execute another statement.
Execution Result:
2. Alias usage
Use aliases to simplify the use of names. Add the configuration information in the Mybatis.xml as follows:
<!-- define aliases --> < typealiases > <!-- type: Source type name alias: target alias The following means to alias "Org.tonny.entity.User" to "User" --> < typealias
type = "Org.tonny.entity.User" alias = "Aliasuser" /> </ typealiases >
I have defined aliases here, simplifying the type org.tonny.entity.User to user. This label should pay attention to the order, after the properties, before the enviroments, otherwise will report the following error.
The complete contents are as follows:
<?XML version= "1.0" encoding= "UTF-8"?><!DOCTYPE Configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" ><Configuration> <!--Specify the database information file - <PropertiesResource= "Db.properties"></Properties> <!--Defining aliases - <typealiases> <!--type: Source type name alias: target alias The following means to alias "Org.tonny.entity.User" to "User" - <Typealiastype= "Org.tonny.entity.User"alias= "User" /> </typealiases> <!--database environment Configuration if and spring integration does not need to be configured, it is completely given to spring - <!--multiple databases can be configured in environments, but only one is used at the same time. The default identifies the currently used database, and the current default is to use MySQL - <Environmentsdefault= "MySQL"> <EnvironmentID= "MySQL"> <!--The transaction manager, which currently uses only the MyBatis framework, uses the JDBC transaction manager. If you are integrating with spring, you can use the Spring transaction manager - <TransactionManagertype= "JDBC" /> <!--Configure database connection information, connect using database connection pooling (Pooled) - <DataSourcetype= "Pooled"> < Propertyname= "Driver"value= "${driver}" /> < Propertyname= "url"value= "${url}" /> < Propertyname= "username"value= "${name}" /> < Propertyname= "Password"value= "${password}" /> </DataSource> </Environment> </Environments> <!--Manage mapping files for each table - <mappers> <!--The configuration file for each table needs to be loaded in, using resource to introduce - <MapperResource= "Org/tonny/mapper/usersmapper.xml" /> <MapperResource= "Org/tonny/mapper/personmapper.xml" /> </mappers></Configuration>
This allows for use, and the following code configures the way the data is queried by means of aliases.
<id= "Getuserbymapusingalias" parametertype= "Java.util.Map" resulttype= "user"> select * from users WHERE Id=#{id} and Name like #{name} </Select>
The test code is as follows:
@Test Public void Getuserbymapusingalias () { = sqlsessionfactory.opensession (); // identity string for mapping sql String sql = "Org.tonny.mapper.UsersMapper.getUserByMapUsingAlias"; MapNew hashmap<string, object>(); Param.put ("id", 1); Param.put ("name", "%chien%"); List<User> userlist = sqlsession.selectlist (sql, param); Sqlsession.close (); System.out.println (userlist); }
Execution Result:
Postscript
The content recorded today is relatively small, continue tomorrow ....
MyBatis Study (iii)