Dao层:
public interface IUserDao { /**
* 查询所有结果
* @return
*/
@Select("select * from user")
List<User> findAll(); /**
* 保存用户
* @param user
*/
@Insert("insert into user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user); /**
* 更新用户
* @param user
*/
@Update("update user set username = #{username},address = #{address},sex = #{sex},birthday = #{birthday} where id = #{id}")
void updateUser(User user); /**
* 删除用户
* @param id
*/
@Delete("delete from user where id = #{id}")
void deleteUser(Integer id); /**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id = #{id}")
User findById(Integer userId); /**
* 根据用户模糊查询
* @param username
* @return
*/
// @Select("select * from user where username like #{username}") //参数占位符
@Select("select * from user where username like '%${value}%'") //字符串拼接
List<User> findUserByName(String username); /**
* 查询总用户数量
* @return
*/
@Select("select count(*) from user")
int findTotalUser(); }
test:
public class AnnotationCRUDTest { private InputStream in;
private SqlSessionFactory factory;
private SqlSession session;
private IUserDao userDao; @Before
public void init() throws IOException {
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userDao = session.getMapper(IUserDao.class);
} @After
public void destory() throws IOException {
session.commit();
session.close();
in.close();
} @Test
public void testSave(){
User user = new User();
user.setUsername("flypig");
user.setAddress("中国"); userDao.saveUser(user);
} @Test
public void testUpdate(){
User user = new User();
user.setId(49);
user.setUsername("flypighhh");
user.setAddress("China");
user.setSex("男");
user.setBirthday(new Date()); userDao.updateUser(user);
} @Test
public void testDelete(){
userDao.deleteUser(49);
} @Test
public void testFindOne(){
User user = userDao.findById(48);
System.out.println(user);
} @Test
public void testFindUserByName(){
//List<User> users = userDao.findUserByName("%王%");
List<User> users = userDao.findUserByName("王");
for (User user : users) {
System.out.println(user);
}
} @Test
public void testFindTotal(){
int total = userDao.findTotalUser();
System.out.println(total);
} }
解决实体类属性和数据库表字段不对应:
@Results(id="userMap",value={
@Result(id=true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "address",property = "userAddress"),
@Result(column = "sex",property = "userSex"),
@Result(column = "birthday",property = "userBirthday"),
}) //其他可根据id调用
@ResultMap(value={"userMap"})
//@ResultMap("userMap")