sprngboot整合Mybatis(注解开发)

官方说明MyBatis-Spring-Boot-Starter will help you use MyBatis with Spring Boot 

其实就是myBatis看spring boot这么火热,为了迎合springboot也开发出一套解决方案来凑凑热闹, mybatis-spring-boot-starter,这个jar包含了mybatis核心包以及mybatis自动配置类。

开发步骤

1:pom依赖

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

               <!-- mybatis-起步依赖 -->

        <dependency>

            <groupId>org.mybatis.spring.boot</groupId>

            <artifactId>mybatis-spring-boot-starter</artifactId>

            <version>1.3.1</version>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

         

         

        <!-- druid 起步依赖 -->

        <dependency>

            <groupId>com.alibaba</groupId>

            <artifactId>druid-spring-boot-starter</artifactId>

            <version>1.1.6</version>

        </dependency>

        <!-- mysql数据库驱动 -->

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <scope>runtime</scope>

        </dependency>    

        

 

注意:当你做了pom依赖就立马启动工程,那么启动会报错,为什么呢?因为Mybatis-springboot-starter在自动化配置的时候,需要使用到datasource,但是容器中还没有datasource(因为你都没告诉springboot你的数据库信息)所以第二步就是配置数据库信息

2:配置数据库信息

1

2

3

4

5

#jdbc配置

spring.datasource.druid.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8

spring.datasource.druid.username=root

spring.datasource.druid.password=root

spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver

 

3:功能开发

功能一:根据用户id查询用户信息

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

package com.wendao.demo.pojo;

 

import java.util.Date;

import java.util.List;

 

public class User {

    private Integer id;

 

    private String username;

 

    private Date birthday;

 

    private String sex;

 

    private String address;

 

    private List<Orders> orders;

     

     

     

     

    public List<Orders> getOrders() {

        return orders;

    }

 

    public void setOrders(List<Orders> orders) {

        this.orders = orders;

    }

 

    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 == null null : username.trim();

    }

 

    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 == null null : sex.trim();

    }

 

    public String getAddress() {

        return address;

    }

 

    public void setAddress(String address) {

        this.address = address == null null : address.trim();

    }

}

 

mapper接口

1

2

3

4

5

6

7

8

9

10

11

package com.wendao.demo.mapper;

import org.apache.ibatis.annotations.Select;

 

import com.wendao.demo.pojo.User;

 

import scala.annotation.meta.param;

public interface UserMapper {

     

    @Select("select * from user where id=#{id}")

    public User getUserById(int id);

}  

 

测试:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@RunWith(SpringRunner.class)

@SpringBootTest

public class Springboot03MybatisApplicationTests {

 

    @Autowired

    private UserMapper userMapper;

    @Test

    public void contextLoads() {

         

        System.out.println(userMapper.getUserById(22).getUsername());

    }

     

     

}

测试结果报错,报错的原因是容器中没有userMapper对象,因为你只写了接口但是没扫描,扫描方式两种

1:全局扫描,在引导类加上@MapperScan注解

2018-03-04_130243.png

 

2:逐个扫描

2018-03-04_130343.png

 

注意,如果数据库字段和属性名不一致,需手动映射

1

2

3

4

5

@Results({  

    @Result(id=true,property="id",column="id"),  

    @Result(property="name",column="name1"),  

    @Result(property="age",column="age1")  

})

 

 

 

功能2:添加用户

1

2

@Insert("insert into user (username,sex)values(#{username},#{sex})")

public void addUser(@Param("username")String username,@Param("sex")char sex);

功能3:添加用户

1

2

@Insert("insert into user (username,sex)values(#{username},#{sex})")

public void addUser1(User user);

功能4:更新用户

1

2

@Update("update user set username=#{username} where id=#{id}")

public void updateUser(@Param("username")String username,@Param("id")int id);

功能5:删除用户

1

2

@Delete("delete from user where id=#{id}")

public void deleteById(int id);

功能6:添加用户成功后返回主键

1

2

3

@Insert("insert into user (username,sex)values(#{username},#{sex})")

@Options(useGeneratedKeys = true, keyProperty = "id")

public void addUser3(User user);

 

注解只需了解基本单表增删改查即可,如果想进一步了解,请参考http://www.mybatis.org/mybatis-3/zh/java-api.html

 

 

Spring Boot整合MyBatis可以使用注解开发,以下是基本的步骤: 步骤1:添加依赖 在pom.xml文件中添加Spring Boot和MyBatis的依赖: ```xml <dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <!-- 数据库驱动,根据自己使用的数据库选择对应的驱动 --> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> ``` 步骤2:配置数据源 在application.properties或application.yml文件中配置数据库连接信息: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 步骤3:创建实体类和Mapper接口 创建对应的实体类和Mapper接口,使用注解指定SQL语句和参数映射关系。例如: ```java public interface UserMapper { @Select("SELECT * FROM users WHERE id = #{id}") User findById(@Param("id") Long id); // 其他方法... } ``` 步骤4:创建MyBatis配置类 创建一个MyBatis的配置类,用于注入Mapper接口。例如: ```java @Configuration @MapperScan("com.example.mapper") public class MyBatisConfig { } ``` 步骤5:运行Spring Boot应用程序 在启动类上添加`@SpringBootApplication`注解,然后运行Spring Boot应用程序。 现在,你可以在其他类中注入并使用Mapper接口了。例如: ```java @Service public class UserService { private final UserMapper userMapper; public UserService(UserMapper userMapper) { this.userMapper = userMapper; } public User findUserById(Long id) { return userMapper.findById(id); } // 其他方法... } ``` 以上就是使用注解开发的Spring Boot整合MyBatis的基本步骤。你可以根据实际需求进行扩展和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值