Mybatis simple add delete change check
This is the 25th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Mybatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all of the JDBC code and manual parameter setting and result set extraction. MyBatis uses simple XML or annotations to configure and map the base body, mapping interfaces and Java’s POJOs(Plain Old Java Objects) to records in the database.
Tools: Navicat Premium, IntelliJ IDEA
Simple directory structure
1. Create the mysql database
Create a firenD_MQ database, create a table named Users, and insert some data
2. Create a Maven project and import the dependencies
<dependencies>
<! -- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<! Add myBatis dependency -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<! - a JDBC driver - >
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<! -- Junit Test class -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
Copy the code
3. Create mybatis-config. XML under resources folder and write the core configuration file of Mybaits
<! DOCTYPEconfiguration
PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<! -- Configuration Core configuration file -->
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/firend_mq? useSSL=false&useUnicode=&characterEncodeing=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<! - registered mapper -- -- >
<mappers>
<mapper resource="dao/UserMapper.xml"/>
</mappers>
</configuration>
Copy the code
IntelliJ IDEA: “/” mysql > connect to mysql. mysql > connect to mysql. mapper: “/”
4. Write myBatis utility class
//SqlSessionFactory
public class Mybatisutil {
private static SqlSessionFactory sqlSessionFactory;
static {
try {// Use mybaatis to get the SqlSessionFactory object
String resource="mybatis-config.xml";
InputStream inputStream= Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch(IOException e) { e.printStackTrace(); }}// With SqlSessionFactory, as the name implies, we can get an instance of SqlSession from it. SqlSession
// Provides all the methods needed to execute SQL commands in the database. You can use the SqlSession instance to execute the mapped SQL statement directly
public static SqlSession getSqlSession(a){
SqlSession sqlSession = sqlSessionFactory.openSession();
returnsqlSession; }}Copy the code
5. Write myBatis entity class
package pojo;
public class User {
private int id;
private String username;
private String password;
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public User(a) {}public int getId(a) {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername(a) {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword(a) {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString(a) {
return "User{" +
"id=" + id +
", username='" + username + '\' ' +
", password='" + password + '\' ' +
'} '; }}Copy the code
The preparatory work has been completed and the code has begun
6. Write the Dao layer interface
public interface UserDao {
// Query all users
List<User> getUserList(a);
// Query the user with the specified ID
User getUserById(int id);
// Add a user
int addUser(User user);
// Modify the user
int updateUser(User user);
// Delete a user
int deleteUser(int id);
}
Copy the code
The interface implementation class is changed from UserDaoImpl to Mapper configuration folder
<! -- Namespace = bind a corresponding Dao/Mapper interface -->
<mapper namespace="dao.UserDao">
<! Select * from 'select';
<select id="getUserList" resultType="pojo.User">
select * from firend_mq.users
</select>
<! -- query by id -->
<select id="getUserById" parameterType="int" resultType="pojo.User">
select * from firend_mq.users where id = #{id}
</select>
<! Add an attribute to the user object.
<insert id="addUser" parameterType="pojo.User">
insert into firend_mq.users (id,username,password) value (#{id},#{username},#{password})
</insert>
<update id="updateUser" parameterType="pojo.User">
update firend_mq.users set username=#{username},password=#{password} where id=#{id};
</update>
<! -- Delete a user -->
<delete id="deleteUser" parameterType="int">
delete from firend_mq.users where id=#{id}
</delete>
</mapper>
Copy the code
Note:
- Mapper configuration files must be registered in mybatis-config.xml
- Tags are the type of add, delete, change, and check. In the tag, write the original SQL statement, using #{} to pass the value
- Namespace = Bind a corresponding Dao/Mapper interface. Do not bind an incorrect interface
- Id is the name of the method in the interface
- ParameterType is the parameterType of a method. ResultType is the return value type of a method.
8. Write test classes
public class UserDaoText {
// Query all users
@Test
public void getUserList(a){
// Step 1: Get the sqlSession object
SqlSession sqlSession = Mybatisutil.getSqlSession();
// Method 1: getMapper
UserDao mapper = sqlSession.getMapper(UserDao.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
// Query the user with the specified ID
@Test
public void getUserById(a){
SqlSession sqlSession = Mybatisutil.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
User user = mapper.getUserById(2);
System.out.println(user);
sqlSession.close();
}
// All additions, deletions and changes must be committed to the transaction
// Add a user
@Test
public void addUser(a){
SqlSession sqlSession = Mybatisutil.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.addUser(new User(4."Zhang"."10086"));
// Commit the transaction
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(a){
SqlSession sqlSession = Mybatisutil.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.updateUser(new User(4."Ha ha"."123"));
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(a){
SqlSession sqlSession = Mybatisutil.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
mapper.deleteUser(4); sqlSession.commit(); sqlSession.close(); }}Copy the code
Such a simple Mybatis to add, delete, change, check is finished, details are annotated in the code.