MyBatis的注解,主要是用于替换映射文件。映射文件中无非存放在增删改查的sql映射标签。所以,MyBatis注解,就是要替换映射文件中的SQL标签。
MyBatis官方文档中指出,若要真正想发挥MyBatis功能,还是要用映射文件。所以官方并不建议使用MyBatis注解式开发。
MyBatis的注解主要是在接口方法的的上面的 注意的是注解括号后面不需要打分号。
接口类 ↓
/**
*新增
**/
@Insert("INSERT INTO `books`.`t_user` (`uid`, `uname`, `upwd`) VALUES(#{uid},#{uname}, #{upwd}) ")
public void adduser(t_user user);
/**
*修改
**/
@Update("UPDATE t_user SET uname = #{uname}, upwd = #{upwd} WHERE uid = #{uid}")
public void edituser( t_user user);
/**
*删除
**/
@Delete("DELETE FROM t_user WHERE `uid` = #{uid}")
public void deleteuser(String uid);
/**
*条件查询
**/
@Select(" select * from t_user where uname=#{uname}")
public t_user alluserByname(String uname);
/**
*查询所有
**/
@Select("select * from t_user")
public List<t_user> alluser();
实现类 ↓
/**
*查询
**/
@Test
public void Alluser() throws Exception {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
It_user t = sqlSession.getMapper(It_user.class);
List<t_user> users = t.alluser();
System.out.println(users);
sqlSession.close();
}
/**
*条件查询
**/
@Test
public void AlluserByname() throws Exception {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
It_user t = sqlSession.getMapper(It_user.class);
t_user user = t.alluserByname("1111");
System.out.println(user);
sqlSession.close();
}
/**
*新增
**/
@Test
public void adduser() throws Exception {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
It_user t = sqlSession.getMapper(It_user.class);
t.adduser(new t_user(String.valueOf(UUID.randomUUID()), "5", "1"));
sqlSession.commit();
sqlSession.close();
}
/**
*修改
**/
@Test
public void edituser()throws Exception{
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
It_user t = sqlSession.getMapper(It_user.class);
t.edituser(new t_user("21244f5e-3621-4178-9e60-8e1ec6f9b121","www","eeee"));
sqlSession.commit();
sqlSession.close();
}
/**
*删除
**/
@Test
public void deleteuser() throws Exception{
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
It_user t = sqlSession.getMapper(It_user.class);
t.deleteuser("21244f5e-3621-4178-9e60-8e1ec6f9b121");
sqlSession.commit();
sqlSession.close();
}
上面就是 mybatis 的注解 如有不足 欢迎大路大神 指出!!!!!