通用 Mapper 封装

通用 Mapper 封装

首先在maven项目,在pom.xml中引入mapper的依赖

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

space.terwer

mybatis-general-mapper

1.0-SNAPSHOT

jar

mybatis-general-mapper

http://maven.apache.org

UTF-8

UTF-8

17

17

17

org.mybatis

mybatis

3.5.6

org.jboss

jboss-vfs

3.2.15.Final

mysql

mysql-connector-java

8.0.28

runtime

io.mybatis

mybatis-mapper

2.2.5

io.mybatis

mybatis-service

2.2.5

io.mybatis

mybatis-jakarta-jpa

2.2.5

junit

junit

4.13.2

test

插一句,答疑解惑:什么是Active Record模式?

Active Record模式

说一说 ActiveRecord 模式的应用场景。

在一个简单的增删改查系统中,如果用不到 service 层,那就可以直接在 controller 层用实体类进行直接的CRUD。

但是在一个有 service 层的系统中,如果要实现模块的隔离,就需要考虑实体类只能在 service 层使用, 不能让实体类逸出到其他层,因此在和 controller 层交互时就需要有 VO 或 DTO 进行数据转换, 这样才能保证实体类调用 CRUD 方法不出错。

Mybatis配置文件中完成配置

实体类设置主键

/**

* @author terwer on 2024/12/4

*/

@Entity.Table("user")

public class User {

@Entity.Column(id = true)

private Integer id;

private String username;

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;

}

}

测试代码

/**

* @author terwer on 2024/12/4

*/

public class UserTest {

@Test

public void test1() throws IOException {

InputStream resourceAsStream =

Resources.getResourceAsStream("sqlMapConfig.xml");

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

try (SqlSession sqlSession = sqlSessionFactory.openSession()) {

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

User user = new User();

user.setUsername("测试4");

user.setId(4);

// insert 接口

// 保存一个实体,null值也会保存,不会使用数据库默认值

userMapper.insert(user);

sqlSession.commit();

}

}

}

结果如下:

Checking to see if class space.terwer.mapper.UserMapper matches criteria [is assignable to Object]

cacheKey - space.terwer.mapper.UserMapper.insert :

Opening JDBC Connection

Created connection 527829831.

Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1f760b47]

==> Preparing: INSERT INTO user(id,username) VALUES (?,?)

==> Parameters: 4(Integer), 测试4(String)

<== Updates: 1

Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@1f760b47]

相关数据