Spring Boot 4 MyBatis
SpringBoot内使用MyBatis,可以不使用xml映射配置,通过注解方式映射。
pom.xml添加依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency>
在application.properties配置文件中添加
spring.datasource.url=jdbc:mysql://localhost:3306/test2
spring.datasource.username=root
spring.datasource.password=hongda$123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
这样配置,可以操作数据库中的数据,但是表跟数据库必须自己创建,跟Hibernate有点不一样。
使用MyBatis:
public class User { private Long id; private String name; private Integer age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
操作:
@Mapper public interface UserMapper { @Select("SELECT * FROM user WHERE name = #{name}") User findByName(@Param("name") String name); @Results({ @Result(property = "name", column = "name"), @Result(property = "age", column = "age") }) @Select("SELECT name, age FROM user") List<User> findAll(); @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})") int insert(@Param("name") String name, @Param("age") Integer age); @Update("UPDATE user SET age=#{age} WHERE name=#{name}") void update(User user); @Delete("DELETE FROM user WHERE id =#{id}") void delete(Long id); @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})") int insertByUser(User user); @Insert("INSERT INTO user(name, age) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})") int insertByMap(Map<String, Object> map); }
运行:
@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) @Transactional public class ApplicationTests { @Autowired private UserMapper userMapper; @Test @Rollback public void testUserMapper() throws Exception { // insert一条数据,并select出来验证 userMapper.insert("AAA", 20); User u = userMapper.findByName("AAA"); Assert.assertEquals(20, u.getAge().intValue()); // update一条数据,并select出来验证 u.setAge(30); userMapper.update(u); u = userMapper.findByName("AAA"); Assert.assertEquals(30, u.getAge().intValue()); // 删除这条数据,并select验证 userMapper.delete(u.getId()); u = userMapper.findByName("AAA"); Assert.assertEquals(null, u); u = new User("BBB", 30); userMapper.insertByUser(u); Assert.assertEquals(30, userMapper.findByName("BBB").getAge().intValue()); Map<String, Object> map = new HashMap<>(); map.put("name", "CCC"); map.put("age", 40); userMapper.insertByMap(map); Assert.assertEquals(40, userMapper.findByName("CCC").getAge().intValue()); List<User> userList = userMapper.findAll(); for(User user : userList) { Assert.assertEquals(null, user.getId()); Assert.assertNotEquals(null, user.getName()); } } }