Introduction to Mybatis - add, delete, modify and query a single table based on configuration
Use steps (all xml configurations have been configured)
Introduction to Mybatis
Official website link: https://mybatis.org/mybatis-3/zh/index.html . More detailed information can be viewed on the official website.
MyBatis is an excellent persistence layer framework, which supports custom SQL, stored procedures and advanced mapping. MyBatis eliminates almost all JDBC code and the work of setting parameters and obtaining result sets. MyBatis can configure and map primitive types, interfaces and Java POJO s (Plain Old Java Objects) to records in the database through simple XML or annotations.
To use MyBatis, simply mybatis-x.x.x.jar The file can be placed in the classpath.
If you use Maven to build a project, you need to put the following dependent code in POM XML file:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>x.x.x</version> </dependency>
Configuration steps
1. Introduce the jar package of Mybatis
2. Write entity class and DAO interface
3. Add the main configuration file (configure mysql environment, transaction type, data source, basic information of database connection, location of mapping file)
4. Add the mapping file of DAO interface (you need to indicate the location of DAO interface and make a mapping for each method). Note: the path is under the Resource folder, and the directory path needs to be the same as the hierarchy of DAO
5. Use mybatis framework
Use steps (all xml configurations have been configured)
1. Read the configuration file and use the Resources class encapsulated by mybatis.
2. Create SQLSessionFactory factory
3. Use the factory to produce SQLsession objects
4. Use SQLSession to create the proxy object of DAO interface
5. Use the proxy object to execute the method
6. Commit transactions and release resources
Basic data
Entity class
public class User implements Serializable { /** * Java Why should entity classes implement Serializable interfaces * 1.Used for serialization and deserialization -- only when a class implements the Serializable interface can its objects be serialized. * 2.Serializable Interface is a mechanism provided by Java for efficient remote sharing of instance objects. You can implement this interface. */ private Integer id; private String username; private Date birthday; private String sex; private String address; 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 + '\'' + '}'; }
Interface of DAO layer
public interface IUserDao { /** * Query all * @return All User information */ //@Select("select * from User") List<User> findAll(); /** * Save operation * @param user */ //@Insert("insert into User(username,address,sex,birthday)values()") void saveUser(User user); /** * Change operation */ void updateUser(User user); /** * Delete operation * @param i */ void deleteUser(Integer i); /** * Query a single user by id * @param id * @return */ User findById(Integer id); /** * Fuzzy query by name * @param name * @return */ List<User> findByName(String name); /** * Total number of query users * @return */ int findTotal(); }
Master profile
<?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"> <!--myBatis Master profile for --> <configuration> <!--Configuration environment--> <environments default="mysql"> <!--to configure mysql environment--> <environment id="mysql"> <!--Configure the type of transaction--> <transactionManager type="JDBC"></transactionManager> <!--Configure data source (connection pool)--> <dataSource type="POOLED"> <!--Configure basic information for connecting to the database--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/eesy"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!--Mapping file configuration file mode--> <mappers> <mapper resource="com/dynamic_basics/dao/IUserDao.xml"></mapper> </mappers> <!--Mapping file annotation method(To use annotations, you need to delete the source configuration file)--> <!-- <mappers> <mapper class="com.dynamic_basics.dao.IUserDao"></mapper> </mappers>--> </configuration>
Sub profile
<?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="com.dynamic_basics.dao.IUserDao"> <!--Use configuration to solve the problem Java Inconsistency between entity class and database column name--> <resultMap id="userMap" type="com.dynamic_basics.domain.User"> <!--Primary key field--> <id property="userId" column="id"></id> <!--Non primary key field--> <result property="userName" column="username"></result> <result property="userAddress" column="address"></result> <result property="userSex" column="sex"></result> <result property="userBirthday" column="birthday"></result> </resultMap> <!--Query all id Use method name--> <select id="findAl l" resultType="com.dynamic_basics.domain.User" resultMap="userMap"> select * from user </select> <!--Save user--> <insert id="saveUser" parameterType="com.dynamic_basics.domain.User"> <!--Parameter used ognl expression--> insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday}); </insert> <!--Update user--> <insert id="updateUser" parameterType="com.dynamic_basics.domain.User"> update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id} </insert> <!--delete user--> <delete id="deleteUser" parameterType="int"> delete from User where id=#{id} </delete> <!--according to id Query user--> <select id="findById" parameterType="int" resultType="com.dynamic_basics.domain.User"> select * from user where id=#{id} </select> <!--Fuzzy query by name--> <select id="findByName" resultType="com.dynamic_basics.domain.User" parameterType="String"> select * from user where username like #{name} </select> <!--Get the total number of user records--> <select id="findTotal" resultType="int"> SELECT COUNT(id) FROM `user`; </select> </mapper>
Test class
/** * @Author: Promsing * @Date: 2021/3/29 - 8:58 * @Description: Description Description * @version: 1.0 */ public class MyBatisTest { private InputStream in; private SqlSession sqlSession; private IUserDao userDao; @Before public void init()throws Exception{ //1. Read the configuration file. Resources is a class encapsulated by myBatis in= Resources.getResourceAsStream("SqlMapConfig.xml"); //2. Create SQLSessionFactory factory // SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is); SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder(); SqlSessionFactory factory=builder.build(in); //3. Use the factory to produce SQLSession objects sqlSession = factory.openSession(); //4. Use SQLSession to create the proxy object of DAO interface userDao = sqlSession.getMapper(IUserDao.class); } @After public void destory()throws Exception{ //6. Release resources //Commit transaction sqlSession.commit(); sqlSession.close(); in.close(); } //Introductory case /** * Query operation */ @Test public void selectUser(){ //Initialize resource - use annotation Before //5. Use the proxy object to execute the method List<User> all = userDao.findAll(); for (User user : all) { System.out.println(user); } //Free resources - use annotation After } /** * Test save */ @Test public void testSave() { User user=new User(); user.setUsername("mybatis"); user.setAddress("Yanqing District, Beijing"); user.setSex("female"); user.setBirthday(new Date()); //Initialize resource - use annotation Before //5. Use the proxy object to execute the method userDao.saveUser(user); //Free resources - use annotation After } /** * Test modification */ @Test public void testUpdate() { User user=new User(); user.setId(50); user.setUsername("mybatis_plus"); user.setAddress("Beijing anci"); user.setSex("male"); user.setBirthday(new Date()); //Initialize resource - use annotation Before //5. Use the proxy object to execute the method userDao.updateUser(user); //Free resources - use annotation After } /** * Test delete */ @Test public void testDelete() { //Initialize resource - use annotation Before //5. Use the proxy object to execute the method userDao.deleteUser(50); //Free resources - use annotation After } /** * Query individual employee information */ @Test public void testFindById() { //Initialize resource - use annotation Before //5. Execution method of agent object User user=userDao.findById(49); System.out.println(user); //Free resources - use annotation After } /** * Fuzzy query */ @Test public void testFindByName() { //Initialize resource - use annotation Before //5. Use the proxy object to execute the method List<User> users=userDao.findByName("%king%"); users.forEach(i-> System.out.println(i)); //Free resources - use annotation After } /** * Total records of test query */ @Test public void testFindTotal() { //Initialize resource - use annotation Before //5. Use the proxy object to execute the method int total=userDao.findTotal(); System.out.println(total); //Free resources - use annotation After } }
summary
In fact, the method used by mybatis is very simple. You need to remember more configurations. When the configuration is done, it is very simple to use. Mybatis framework encapsulates the complex registration driver and connection acquisition in JDBC using different service classes (DriverManager,Connection,Statement,ResultSet). In fact, learning the framework is the stage of understanding the framework, getting familiar with the configuration and using the framework.
For a detailed explanation of the specific configuration, please go to mybatis Official website
If this blog is helpful to you, please remember to leave a message + like + collect. Original is not easy, please contact the author for reprint!