The statement

This blog is based on the relevant dark horse programmers of the course summary, interested in can go to see the video tutorial, no nonsense, or more recommended. This blog is actually a summary of the previous Mybatis, with the more commonly used method in the form of ———— annotations.

The planned content of this blog is:

  1. The construction of the environment
  2. Single table CRUD operation
  3. Multiple table query operations
  4. Configuration of cache

0 Database preparation

1 Environment Construction

1.1 Create a new Maven project

Introduce the dependency code needed in the POM.xml file:

<? The 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 > org. Example < / groupId > < artifactId > day04_eesy_03annotation_mybatis < / artifactId > < version > 1.0 - the SNAPSHOT < / version > < packaging > jar < / packaging > <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId> <version>4.10</version> <scope>test</scope> </dependency> </dependencies> <! -- This is a solution to an error that I encountered later in the runtime. Release 5 --> <properties> <java.version>11</java.version> <maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.target>${java.version}</maven.compiler.target> </properties> </project>Copy the code

Also: Java: Error: The fix for the release 5 issue is listed above

1.2 CRUD Operations on a Single table

1.2.1 Creating entity-class objects and creating persistence layer interfaces

package com.zhouman.domain; import java.io.Serializable; import java.util.Date; public class User implements Serializable { private Integer id; private String username; private String address; private String sex; private Date birthday; @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", address='" + address + '\'' + ", sex='" + sex + '\'' + ", birthday=" + birthday + '}'; } 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 String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; }}Copy the code
package com.zhouman.dao; import com.zhouman.domain.User; import java.util.List; Public interface IUserDao {/** * query all users * @return */ List<User> findAll(); }Copy the code

1.2.2 Writing a Master Configuration File

Notice that it’s under the Resource package

Properties and jdbcconfig. properties are the four types of information needed to connect data to log4j.properties.

SqlMapConfig. XML:

<? The 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> <! <properties resource=" jdbcconfig. properties"></properties> <! -- Configure aliases --> <typeAliases> <package name="com.zhouman.domain"/> </typeAliases> <! --> <environment default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <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> <! <mappers> <package name="com.zhouman.dao"/> </mappers> </configuration>Copy the code

1.2.3 Add corresponding annotations before method bodies in DAO persistence layer interfaces.

In Mybatis, CRUD has four annotations: @select @insert @update @delect

Take the findAll method as an example:

package com.zhouman.dao; import com.zhouman.domain.User; import org.apache.ibatis.annotations.Select; import java.util.List; Public interface IUserDao {@return */ @select (" Select * from user") List< user > findAll(); }Copy the code

1.2.4 Write test classes for testing

  1. Gets a byte input stream
  2. Create an SqlSessionFactory from a byte input stream
  3. Produce a SqlSession based on SqlSessionFactory
  4. Get the Dao’s proxy object using SqlSession
  5. Executing Dao methods
  6. Release resources
package com.zhouman.test; import com.zhouman.dao.IUserDao; import com.zhouman.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 java.io.IOException; import java.io.InputStream; import java.util.List; Public class MybatisAnnoTest {/** * test mybatis using * @param args */ public static void main(String[] args) throws IOException { //1. Get byte input stream InputStream InputStream = Resources. GetResourceAsStream (" SqlMapConfig. XML "); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); / / 3. According to the production a SqlSession SqlSessionFactory SqlSession SqlSession = sessionFactory. OpenSession (); IUserDao userDao = SQLSession.getMapper (iUserDao.class); //4. List<User> users = userdao.findAll (); for (User user : users){ System.out.println(user); } //6. Sqlsession.close (); inputStream.close(); }}Copy the code

Operation effect:I usually have a problem in the databasejdbcConfig.propertiesMake sure that the information in the file matches the information in your database

1.2.5 Save and update functions in the form of annotations

Save user functionality (that is, add a user)

Create methods and write comments in the IUserDao interface

/ save users * * * * @ param user * / @ Insert (" Insert into user (username, address, sex, birthday) value(#{username},#{address},#{sex},#{birthday})") void saveUser(User user);Copy the code

Create test classes to test methods

package com.zhouman.test; import com.zhouman.dao.IUserDao; import com.zhouman.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; public class AnnotationCRUDTest { private InputStream inputStream; private SqlSessionFactory sessionFactory; private SqlSession sqlSession; private IUserDao userDao; @Before public void init() throws IOException { //1. Get byte input stream inputStream = Resources. GetResourceAsStream (" SqlMapConfig. XML "); SessionFactory = new SqlSessionFactoryBuilder().build(inputStream); / / 3. According to the production a SqlSession SqlSessionFactory SqlSession = sessionFactory. OpenSession (); UserDao = sqlsession.getMapper (iUserDao.class); //4. } @After public void destroy() throws IOException { //6. SqlSession.com MIT (); sqlSession.close(); inputStream.close(); } @Test public void testSave(){ User user = new User(); user.setUsername("annotation"); User.setaddress (" guangzhou Liwan district "); userDao.saveUser(user); }}Copy the code

The use of @after @before is described in the previous blog. Since both methods are used to create the DAO proxy object and destroy the resource, it is possible to simplify the code by putting them separately.

The result of my run looks like this:

That’s because it doesn’t show up in Chinese. In jdbcConfig. The change in the properties file is this: the JDBC. Url = JDBC: mysql: / / localhost: 3306 / eesy_mybatis? useUnicode=true&characterEncoding=utf8

The result of running again after the change:

Update user functions

Create methods in the DAO interface in the form of comments

/** * Update user * @param user */ @update (" Update user set" username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}") void updateUser(User user);Copy the code

Write test methods in the test method class (that is, in the method above)

@Test public void testUpdate(){ User user = new User(); user.setId(57); user.setUsername("uptate"); User.setaddress (" guangzhou University Town "); User. SetSex (" male "); user.setBirthday(new Date()); userDao.updateUser(user); }Copy the code

Execution Result:

The function of deleting users

Create methods in the DAO interface in the form of comments

/** * Delete user * @param userId */ @delete (" Delete from user where id=#{id}") void deleteUser(Integer userId);Copy the code

Write test methods in the test method class (that is, in the method above)

    @Test
    public void testDelete(){
        userDao.deleteUser(58);
        userDao.deleteUser(59);
    }
Copy the code

Execution Result:

Query user functions by ID

Create methods in the DAO interface in the form of comments

/** * Select(" Select * from user where ID = #{id}") user findById(Integer) userId);Copy the code

Write test methods in the test method class (that is, in the method above)

    @Test
    public void testFindById(){
        System.out.println(userDao.findById(57));
        System.out.println(userDao.findById(58));
    }
Copy the code

Execution Result:

Fuzzy query by user name

Create methods in the DAO interface in the form of comments

/** * Select(" Select * from user where username like #{username}") List<User> findByName(String username);Copy the code

Write test methods in the test method class (that is, in the method above)

@test public void testFindByName(){List<User> users = userdao.findByName ("% king %"); for (User user : users){ System.out.println(user); }}Copy the code

The execution result

Example Query the total number of users

Create methods in the DAO interface in the form of comments

@return */ @select (" Select count(*) from user") int findTotalUser();Copy the code

Write test methods in the test method class (that is, in the method above)

    @Test
    public void testTotalUser(){
        int totalUser = userDao.findTotalUser();
        System.out.println(totalUser);
    }
Copy the code

Execution Result:

conclusion

The content of blog stops here, miscellaneous thing is very much recently, change profession is not easy.

  1. Multiple table query operations
  2. Configuration of cache

Save that for my next blog post. Please give it a thumbs up if you see it here!