Overview:
- 1. Preparation
- 2. XML configuration file
- 3. Operation test
- 4. note:
1. Preparation
(1) create a database and user table, account table, role table, role (using mysql) Back to the beginning of the article
#Create mybatis database CREATE DATABASE mybatis; #Use database USE mybatis #Delete user table if it exists DROP TABLE IF EXISTS `user`; #Create user table CREATE TABLE `user` ( `id` int(11) NOT NULL auto_increment, `username` varchar(32) NOT NULL COMMENT 'User name', `birthday` datetime default NULL COMMENT 'Birthday', `sex` char(1) default NULL COMMENT 'Gender', `address` varchar(256) default NULL COMMENT 'address', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; #Insert some test data insert into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (41,'Lao Wang','2018-02-27 17:47:08','male','Beijing'), (42,'Little two kings','2018-03-02 15:09:37','female','Beijing Golden Swallow Dragon'), (43,'Little two kings','2018-03-04 11:34:34','female','Beijing Golden Swallow Dragon') #Delete account table if it exists DROP TABLE IF EXISTS `account`; #Create account table CREATE TABLE `account` ( `ID` int(11) NOT NULL COMMENT 'number', `UID` int(11) default NULL COMMENT 'User number', `MONEY` double default NULL COMMENT 'Amount of money', PRIMARY KEY (`ID`), KEY `FK_Reference_8` (`UID`), CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; #Insert some test data insert into `account`(`ID`,`UID`,`MONEY`) values (1,46,1000),(2,45,1000),(3,46,2000);
(2) entity class User Back to the beginning of the article
package cn.itcast.domain; import java.io.Serializable; import java.util.Date; import java.util.List; public class User implements Serializable { private Integer id;//User unique identification private String username;//User name private Date birthday;//Birthday private String sex;//Gender private String address;//address //For one to many mapping, the primary table entity should contain the set reference of the secondary table entity private List<Account> accounts; public List<Account> getAccounts() { return accounts; } public void setAccounts(List<Account> accounts) { this.accounts = accounts; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", sex='" + sex + '\'' + ", address='" + address + '\'' + ", accounts=" + accounts + ", roles=" + roles + '}'; } }
(3) entity class Account Back to the beginning of the article
package cn.itcast.domain; public class Account { private Integer account_id; private Integer account_uid; private Double account_money; //An account corresponds to a User (one-to-one). A User object reference is defined here private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Integer getAccount_id() { return account_id; } public void setAccount_id(Integer account_id) { this.account_id = account_id; } public Integer getAccount_uid() { return account_uid; } public void setAccount_uid(Integer account_uid) { this.account_uid = account_uid; } public Double getAccount_money() { return account_money; } public void setAccount_money(Double account_money) { this.account_money = account_money; } @Override public String toString() { return "Account{" + "account_id=" + account_id + ", account_uid=" + account_uid + ", account_money=" + account_money + ", user=" + user + '}'; } }
(4) dao.UserDao Back to the beginning of the article
package cn.itcast.dao; import cn.itcast.domain.User; import org.apache.ibatis.annotations.*; import org.apache.ibatis.mapping.FetchType; import java.util.List; /** * In Mybatis, there are four comments for CRUD * @Select,@Insert,@Update,@Delete */ //Enable L2 cache @CacheNamespace(blocking = true) public interface UserDao { /** * Query all users * @returnList<User> */ @Select("select * from user") //Configure the correspondence between the properties of entity classes and database fields //The id of the Results annotation uniquely identifies this mapping table, which can be used by other methods (the method specifies the ResultMap annotation) @Results(id = "defaultMap",value = { //The id is false by default. When it is specified as true, this entity property is the primary key //Property is the property name of entity class, and column is the corresponding database field name @Result(id = true,property = "id",column = "id"), @Result(property = "username",column = "username"), @Result(property = "sex",column = "sex"), @Result(property = "address",column = "address"), @Result(property = "birthday",column = "birthday"), //Multi table query (one to many relationship) @Result(property = "accounts",column = "id", //The "many" attribute is a "many" annotation. It can specify the location of the sql statement of the associated query and whether to enable delayed loading. It represents that the entity class attribute is a collection of associated objects (that is, the collection of objects can only be obtained by querying the database tables with one to many relationships) many = @Many(select = //The select attribute is used to specify the location of the sql statement of the associated query. According to the sql statement defined by the method cn.itcast.dao.AccountDao.findByUid, the value of the column attribute is passed in as the actual parameter of the query condition parameter to execute the sql statement. The fetchType attribute is used to enable the delayed loading or immediate loading. The FetchType.LAZY represents the delayed loading "cn.itcast.dao.AccountDao.findByUid",fetchType = FetchType.LAZY)) }) List<User> findAll(); /** * Query a user by id * @param id * @return User */ @Select("select * from user where id = #{id}") @ResultMap("defaultMap") User findOne(Integer id); /** * Save user * @param user */ @Insert("insert into user(username,sex,address,birthday)values(#{username},#{sex},#{address},#{birthday})") void saveUser(User user); /** * Update user * @param user */ @Update("update user set username=#{username},sex=#{sex},address=#{address},birthday=#{birthday} where id = #{id}") void updateUser(User user); /** * Delete user by id * @param id */ @Delete("delete from user where id = #{id}") void deleteUser(Integer id); /** * Total records queried * @return */ @Select("select count(*) from user") int findTotal(); }
(5) dao.AccountDao Back to the beginning of the article
package cn.itcast.dao; import cn.itcast.domain.Account; import org.apache.ibatis.annotations.*; import org.apache.ibatis.mapping.FetchType; import java.util.List; public interface AccountDao { /** * Query all accounts * @return List<Account> */ @Select("select * from account") @Results(id = "defaultMap",value = { @Result(id = true,property = "account_id",column = "id"), @Result(property = "account_uid",column = "uid"), @Result(property = "account_money",column = "money"), @Result(property = "user",column = "uid", //The One attribute is a One annotation, which can specify the location of the sql statement of the associated query and whether to enable delayed loading. It represents that the entity class property is an associated object (that is, an object that can only be obtained after querying the database table with which it has a One-to-One relationship) one = @One(select = //The select attribute is used to specify the location of the sql statement of the associated query. mybatis will execute the sql statement according to the sql statement defined by cn.itcast.dao.AccountDao.findByUid method, passing in the value of the column attribute as the actual parameter of the query condition parameter, and the fetchType attribute is used to enable the delayed loading or immediate loading, while the fetchType.eagle represents the delayed loading "cn.itcast.dao.UserDao.findOne",fetchType = FetchType.EAGER)) }) List<Account> findAll(); /** * Find an account by id * @param uid * @return Account */ @Select("select * from account where uid = #{uid}") @ResultMap("defaultMap") List<Account> findByUid(Integer uid); }
2.xml configuration file
(1) mybatis-config.xml (under resources directory) Back to the beginning of the article
<?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> <!--Configuration files for storing four basic information of database connection--> <properties resource="jdbcConfig.properties"/> <!--Enable L2 cache globally--> <settings> <setting name="cacheEnabled" value="true"/> </settings> <!--Register aliases for all entity classes, which are case insensitive class names--> <typeAliases><package name="cn.itcast.domain"/></typeAliases> <environments default="dev_mysql"> <!--Development environment mysql To configure--> <environment id="dev_mysql"> <!--Configure transaction type--> <transactionManager type="JDBC"></transactionManager> <!--Configure data source type--> <dataSource type="POOLED"> <!--Quote jdbcConfig.properties Basic information about database connections stored in--> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!--Configuration mapping file--> <mappers> <!--Indicate annotated dao Interface location--> <package name="cn.itcast.dao"/> </mappers> </configuration>
3. Operation test
(1) UserDaoTest Back to the beginning of the article
package cn.itcast; import cn.itcast.dao.UserDao; import cn.itcast.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; public class UserDaoTest { private InputStream in; private SqlSession session; private UserDao userDao; @Before public void init() throws IOException { //1. Get byte input stream of mybatis configuration file in = Resources.getResourceAsStream("mybatis-config.xml"); //2. Use the builder to build SqlSessionFactory object SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //3. Use SqlSessionFactory object to produce SqlSession session = factory.openSession(); //4. Use session to create dao proxy object userDao = session.getMapper(UserDao.class); } @After public void destroy() throws IOException { //Submission of affairs session.commit(); //Release resources session.close(); in.close(); } /** * Test query all users */ @Test public void findAllTest() { List<User> users = userDao.findAll(); for (User user : users) { System.out.println(user); } } /** * Test query a user */ @Test public void findOneTest() { User user = userDao.findOne(46); System.out.println(user); } /** * Test save user */ @Test public void saveUserTest() { User user = new User(); user.setUsername("mybatis_save_user"); user.setBirthday(new Date()); user.setAddress("Jiangsu"); user.setSex("male"); userDao.saveUser(user); } /** * Test update user */ @Test public void updateUserTest() { User user = new User(); user.setUsername("mybatis_update_user"); user.setBirthday(new Date()); user.setAddress("Jiangsu_update"); user.setSex("female"); user.setId(67); userDao.updateUser(user); } /** * Test delete user */ @Test public void deleteUserTest() { userDao.deleteUser(60); } /** * Total number of records in user table of test query */ @Test public void findTotalTest() { int total = userDao.findTotal(); System.out.println("user Total records:common" + total + "strip"); } }
(2) AccountDaoTest Back to the beginning of the article
package cn.itcast; import cn.itcast.dao.AccountDao; import cn.itcast.dao.UserDao; import cn.itcast.domain.Account; import cn.itcast.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class AccountDaoTest { private InputStream in; private SqlSession session; private AccountDao accountDao; @Before public void init() throws IOException { //1. Get byte input stream of mybatis configuration file in = Resources.getResourceAsStream("mybatis-config.xml"); //2. Use the builder to build SqlSessionFactory object SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //3. Use SqlSessionFactory object to produce SqlSession session = factory.openSession(); //4. Use session to create dao proxy object accountDao = session.getMapper(AccountDao.class); } @After public void destroy() throws IOException { //Release resources session.close(); in.close(); } /** * Test and query all accounts */ @Test public void findAllTest() { List<Account> accounts = accountDao.findAll(); for (Account account : accounts) { System.out.println(account); } } /** * Test to query an account according to uid */ @Test public void findOneTest() { List<Account> accounts = accountDao.findByUid(46); for (Account account : accounts) { System.out.println(account); } } }
Note:
project directory structure: Back to the beginning of the article
log4j.properties: Back to the beginning of the article
when writing Sysem.out.prinltn() in the project, it is output to the console. When the project is published to tomcat, there is no console, but it can be seen in the command-line interface, but it is not easy to observe some output results. log4j is an open source and free log processing class library launched by apache. It can not only output the content to the console, but also output the content to the file. Easy to observe.
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=debug, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
jdbcConfig.properties: Back to the beginning of the article
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis?CharacterEncoding=utf-8&serverTimezone=UTC jdbc.username=root jdbc.password=root
pom.xml: Back to the beginning of the article
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.itcast</groupId> <artifactId>Mybatis_day02</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> </project>
Reference: Notes to Mybatis (1) --- explanation of Mybatis basic xml configuration file