MyBatis注解方式就是讲SQL语句直接写在接口上.
优点:对于需求简单的系统,效率较高
缺点:当SQL有变化时都需要重新编译代码.
1.添加注解
最简单的注解有四种 @Select @Insert @Delete @Update
这里演示
Select和Delete
!!都是最简单的操作,复杂的后面再讲
2.编写接口
我这里要操作的是这个表
所以返回的就是这个User 自己建立的类,用来映射数据库中的属性
public interface UserMapper2 {
@Select( "select id,username from user where id = #{id}" )
public User2 getUserByID(int id);
@Delete( "delete from user where id = #{sid}" )
public int deleteUserByID(int sid);
}
直接在接口上编写SQL语句
3.使用
使用注解方式时就不需要在mapper.xml文件中拼接语句了. 删除掉mapper.xml都可以
在mybatis-config.xml中修改mapper标签
将之前的resource改成class 填写接口的位置
<!--注解的方式-->
<mappers>
<mapper class="com.dao.UserDao"></mapper>
</mappers>
基于这张表
public static void main(String[] args) throws IOException {
//mybatis配置文件名
String resource = "mybatis-config.xml";
//通过mybatis提供的Resources类来读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
//通过SqlSessionFactoryBuilder类创建一个SqlSessionFactory工厂实例
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//通过sqlsessionFactory实例创建sqlsession实例
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//通过反射机制来获取对应mapper实例
UserMapper2 mapper = sqlSession.getMapper(UserMapper2.class);
//调用mapper实例下方法
//mapper.deleteUserByID( 27 );
User2 user = mapper.getUserByID(27);
System.out.println(user);
}
删除后
如果你在这里没有删除成功,有可能是在创建sqlSession()的时候没有指定自动提交,在里面加上true就行.