01、spring整合mybatis简单Demo

一、内容介绍

本文主要以为注解的方式来实现spring和mybatis的整合,做到尽量精简不依赖过多的jar,希望给学习的小伙伴提供一些帮助。

二、本文分类

1、pom.xml文件

2、User实体类

3、Mapper接口

4、AppConfig

5、Service业务类

6、Test

7、目录结构

三、pom.xml

<!--spring-core-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.0.9.RELEASE</version>
</dependency>

<!--JDBC驱动包-->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.11</version>
</dependency>

<!--spring-jdbc spring和jdbc整合,提供连接池,不要使用c3po,太重了-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>5.0.9.RELEASE</version>
</dependency>

<!--mybatis-core-->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.4.6</version>
</dependency>

<!--mybatis-spring  spring和mybatis整合jar-->
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis-spring</artifactId>
  <version>1.3.2</version>
</dependency>

各个jar的介绍都在上面加了注释,缺一不可哈。

四、User实体类

public class User{
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

实体类里面就一个id字段。

五、Mapper接口

public interface UserMapper {
    @Select("SELECT * FROM users WHERE id = #{userId}")
    User getUser(@Param("userId") String userId);
}

为了简便,使用了@Select注解,这样就不需要配置mapper.xml配置文件了。

六、AppConfig

@Configuration
@ComponentScan(value = "com.zhongan") 
@MapperScan("com.zhongan.mapper") //这个注解是为了能扫描到UserMapper接口。
public class Appconfig {

    @Bean(name = "dataSource")
    public DataSource dataSource(){
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useSSL=false");
        driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword("root");
        return driverManagerDataSource;
    }

    @Bean(name="sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return  sqlSessionFactoryBean.getObject();
    }
}

需要注意的几个点

1、@ComponentScan(value = "com.zhongan")是为了把Service扫描进去。

2、@MapperScan("com.zhongan.mapper")是为了把UserMapper扫描进去,然后创建代理对象。

七、Service

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User doSomeBusinessStuff(String userId) {
        return this.userMapper.getUser(userId);
    }
}

在业务层注入UserMapper来调用里面的方法。进而执行sql语句。

八、Test

public class UserTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(Appconfig.class);
        UserService userService = annotationConfigApplicationContext.getBean("userService", UserService.class);
        User user = userService.doSomeBusinessStuff("1");
    }
}

九、目录结构

 

本文参考mybatis-spring官方文档:http://mybatis.org/spring/zh/getting-started.html#

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是一个简单的示例,演示如何使用Spring整合MyBatis对数据库进行增删改查操作: 1. 添加依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependencies> <!-- Spring整合MyBatis依赖 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> <!-- MySQL数据库驱动依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> </dependencies> ``` 2. 配置数据源 在 application.properties 文件中添加以下配置: ```properties # 数据库连接配置 spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # MyBatis配置 mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.example.demo.entity ``` 3. 创建实体类 创建一个实体类,例如: ```java public class User { private Integer id; private String name; private Integer age; // 省略getter和setter方法 } ``` 4. 创建Mapper接口 创建一个Mapper接口,例如: ```java public interface UserMapper { // 新增用户 int insert(User user); // 删除用户 int deleteById(Integer id); // 更新用户 int update(User user); // 根据ID查询用户 User selectById(Integer id); // 查询所有用户 List<User> selectAll(); } ``` 5. 创建Mapper XML文件 在 resources/mapper 目录下创建 UserMapper.xml 文件,例如: ```xml <mapper namespace="com.example.demo.mapper.UserMapper"> <!-- 新增用户 --> <insert id="insert" parameterType="User"> insert into user(name, age) values(#{name}, #{age}) </insert> <!-- 删除用户 --> <delete id="deleteById" parameterType="java.lang.Integer"> delete from user where id = #{id} </delete> <!-- 更新用户 --> <update id="update" parameterType="User"> update user set name = #{name}, age = #{age} where id = #{id} </update> <!-- 根据ID查询用户 --> <select id="selectById" resultType="User" parameterType="java.lang.Integer"> select id, name, age from user where id = #{id} </select> <!-- 查询所有用户 --> <select id="selectAll" resultType="User"> select id, name, age from user </select> </mapper> ``` 6. 创建Service接口及实现类 创建一个Service接口及实现类,例如: ```java public interface UserService { // 新增用户 int addUser(User user); // 删除用户 int deleteUserById(Integer id); // 更新用户 int updateUser(User user); // 根据ID查询用户 User getUserById(Integer id); // 查询所有用户 List<User> getAllUsers(); } @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public int addUser(User user) { return userMapper.insert(user); } @Override public int deleteUserById(Integer id) { return userMapper.deleteById(id); } @Override public int updateUser(User user) { return userMapper.update(user); } @Override public User getUserById(Integer id) { return userMapper.selectById(id); } @Override public List<User> getAllUsers() { return userMapper.selectAll(); } } ``` 7. 编写Controller 在Controller中注入UserService,并实现对应的增删改查接口即可。例如: ```java @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @PostMapping("/add") public int addUser(@RequestBody User user) { return userService.addUser(user); } @DeleteMapping("/{id}") public int deleteUserById(@PathVariable Integer id) { return userService.deleteUserById(id); } @PutMapping("/update") public int updateUser(@RequestBody User user) { return userService.updateUser(user); } @GetMapping("/{id}") public User getUserById(@PathVariable Integer id) { return userService.getUserById(id); } @GetMapping("/all") public List<User> getAllUsers() { return userService.getAllUsers(); } } ``` 这样,我们就完成了Spring整合MyBatis对数据库实现增删改查的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

信仰_273993243

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值