java 对象
public class User {
private int id;
private String name;
private UserSexEnum userSex;
private String password;
}
public enum UserSexEnum {
MALE,FEMALE
}
接口
public interface UserMapper {
@Select("SELECT * FROM user")
@Results({
@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
})
List
@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(property = "userSex", column = "user_sex", javaType = UserSexEnum.class),
})
User getOne(Long id);
@Insert("INSERT INTO user(name,password,user_sex) VALUES(#{name}, #{password}, #{userSex})")
void insert(User user);
@Update("UPDATE user SET name=#{name},password=#{password} WHERE id =#{id}")
void update(User user);
@Delete("DELETE FROM user WHERE id =#{id}")
void delete(Long id);
}
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisBootApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testInsert() {
userMapper.insert(new User("zangliang", "a123456", UserSexEnum.MALE));
// Assert.assertEquals(3,userMapper.getAll().size());
}
@Test
public void testQuery() throws Exception {
List
System.out.println(users.toString());
}
@Test
public void testUpdate() throws Exception {
User user = userMapper.getOne(10l);
user.setName("neo");
userMapper.update(user);
Assert.assertTrue(("neo".equals(userMapper.getOne(10l).getName())));
}
}
数据库文件
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`password` varchar(45) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`user_sex` enum('MALE','FEMALE') DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;