@chenbinghua
2018-08-13T16:13:44.000000Z
字数 2631
阅读 790
SpringBoot
项目springdemo1
<!--springboot-mybatis整合包-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!--mysql-jdbc驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
# 连接池配置
spring.datasource.url=jdbc:mysql://localhost/jfinal_demo?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
spring.datasource.password=root
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
springboot会自动加载spring.datasource.*相关配置,数据源就会自动注入到sqlSessionFactory中,sqlSessionFactory会自动注入到Mapper中,对了你一切都不用管了,直接拿起来使用就行了。
以上的配置修改了springboot的默认数据库连接池为druid
在Mysql中创建User表,包含id(BIGINT)、name(INT)、age(VARCHAR)字段。同时,创建映射对象User。
@Getter@Setter@ToString
public class User {
private Long id;
private String name;
private Integer age;
}
创建User映射的操作UserMapper,为了后续单元测试验证,实现插入和查询操作。
@Mapper
public interface UserMapper {
@Select("SELECT * FROM USER WHERE NAME = #{name}")
User findByName(@Param("name") String name);
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springdemo1ApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
@Rollback
public void findByName() throws Exception {
userMapper.insert("bbbc", 20);
User u = userMapper.findByName("bbbc");
System.out.println(u);
}
}
UserMapper.java
去掉@Mapper注解
去掉@Select @Insert注解
最后变成
public interface UserMapper {
User findByName(@Param("name") String name);
int insert(@Param("name") String name, @Param("age") Integer age);
}
因为去掉@Mapper注解,所以Spring找不到该bean
@SpringBootApplication
@MapperScan("com.chen.springdemo1.mapper")
public class Springdemo1Application {
public static void main(String[] args) {
SpringApplication.run(Springdemo1Application.class, args);
}
}
在UserMapper.java同级目录下创建UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chen.springdemo1.mapper.UserMapper">
<select id="findUserById" parameterType="int" resultType="com.chen.springdemo1.domain.User">
select * from user where id=#{id}
</select>
</mapper>
在pom.xml添加
<!--在pom文件中的build标签中添加这段配置,让在src下的资源也能加载到classes目录-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>