springBoot整合MyBatis实现增删改查、1对多关联查询。

第一步,maven myBatis依赖

<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>
<dependencies>
        <!-- web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
例子所需要用到的完整依赖

第二步,在启动代码中,添加myBatis扫描

扫描此包下的所有.java文件  @MapperScan("com.example.demo.dao")
在启动类中添加对mapper包扫描@MapperScan,如果不添加需要每个mapper加个注解也挺麻烦的。
@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class DemoSpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoSpringBootApplication.class, args);
    }
}

第三步,application.yml 配置mysql连接信息

springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对了你一切都不用管了,直接拿起来使用就行了。

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/bet
    username: root
    password: root

第四步,创建表和对应的BO。

需求

一个用户有多本书,一本书只有一个用户

数据库之间并没有做外键关联

user表

user对应的bo

public class User {

    private Integer id;

    private String userName;

    private List<Books> books;
        
        // get set......................

}

 

books表

books对应的bo

public class Books {

    private Integer id;

    private String name;

    private User user;

        // get set .....................
}

 

 

第五步,做一个mapper接口

下图包目录和第二步相匹配,不能搞错。

 

 

   为了减少文章篇幅,直接把查询book和user都放到userMapper中了。

 

@Result注释,如果表字段和bo相匹配(无关大小写),就不需要配置,如果不匹配就需要做一个配置,比如user表中的u_name和bo中userName不匹配,所以需要做一个映射关系
或者在SQL中通过as 来对应BO,项目中可灵活运用。(getAll 通过SQL AS来对应)

 

public interface UserMapper {

    @Select("select user_name as userName from User u")
    public List<User> getAll();

    @Insert("insert into user(user_name) values(#{userName})")
    public void insertUser(User u);

    @Select("select * from books where u_id in (select id from user where u_name = #{uName})")
    @Results({ @Result(column = "u_id", property = "user",
             one=@One(select="com.example.demo.dao.UserMapper.selectById",fetchType=FetchType.EAGER)
            )})
    public List<Books> findByUserName(String uName);
    
    
    @Select("select * from user where id = #{id}")  
    @Results({ 
        @Result(column = "u_name", property = "userName")
    })
    public User selectById(Integer id);  

}

 

 第六步 测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void test() {
        try {
            List<Books> bs = userMapper.findByUserName("老王");
            System.out.println(bs.size());
            for (Books b : bs) {
                System.out.println(b.getName()+":"+b.getUser().getUserName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
2017-08-03 12:59:08.552  INFO 6036 --- [           main] com.example.demo.test.UserTest           : Started UserTest in 4.884 seconds (JVM running for 5.942)
1
springMVC:老王
2017-08-03 12:59:09.242  INFO 6036 --- [       Thread-2] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@c2db68f: startup date [Thu Aug 03 12:59:04 CST 2017]; root of context hierarchy

 

posted @ 2017-08-03 13:46  xiaomaha  阅读(2387)  评论(0)    收藏  举报