mybatis CRUD
来源:互联网 发布:禁止 域名 ip 编辑:程序博客网 时间:2024/06/05 02:08
除了XML配置,还有注解方式
首先,
/**
* @author gacl
* 定义sql映射的接口,使用注解指明方法要执行的SQL
*/
public interface UserMapperI {
//使用@Insert注解指明add方法要执行的SQL
@Insert("insert into users(name, age) values(#{name}, #{age})")
public int add(User user);
//使用@Delete注解指明deleteById方法要执行的SQL
@Delete("delete from users where id=#{id}")
public int deleteById(int id);
//使用@Update注解指明update方法要执行的SQL
@Update("update users set name=#{name},age=#{age} where id=#{id}")
public int update(User user);
//使用@Select注解指明getById方法要执行的SQL
@Select("select * from users where id=#{id}")
public User getById(int id);
//使用@Select注解指明getAll方法要执行的SQL
@Select("select * from users")
public List<User> getAll();
}
需要说明的是,我们不需要针对UserMapperI接口去编写具体的实现类代码,这个具体的实现类由MyBatis帮我们动态构建出来,我们只需要直接拿来使用即可。
同时,在conf.xml文件中注册这个映射接口:
<mappers>
<!-- 注册userMapper.xml文件,
userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml-->
<mapper resource="me/gacl/mapping/userMapper.xml"/>
<!-- 注册UserMapper映射接口-->
<mapper class="me.gacl.mapping.UserMapperI"/>
</mappers>
使用时:
SqlSession sqlSession = MyBatisUtil.getSqlSession(true);
//得到UserMapperI接口的实现类对象,UserMapperI接口的实现类对象由sqlSession.getMapper(UserMapperI.class)动态构建出来
UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
User user = new User();
user.setName("用户xdp");
user.setAge(20);
int add = mapper.add(user);
//使用SqlSession执行完SQL之后需要关闭SqlSession
sqlSession.close();
System.out.println(add);
public class MyBatisUtil {
/**
* 获取SqlSessionFactory
* @return SqlSessionFactory
*/
public static SqlSessionFactory getSqlSessionFactory() {
String resource = "conf.xml";
InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
return factory;
}
/**
* 获取SqlSession
* @return SqlSession
*/
public static SqlSession getSqlSession() {
return getSqlSessionFactory().openSession();
}
/**
* 获取SqlSession
* @param isAutoCommit
* true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
* false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
* @return SqlSession
*/
public static SqlSession getSqlSession(boolean isAutoCommit) {
return getSqlSessionFactory().openSession(isAutoCommit);
}
}
0 0
- mybatis CRUD
- mybatis (CRUD)
- MyBatis实现CRUD
- mybatis 简单CRUD
- Mybatis小试CRUD
- MyBatis 3 ,CRUD service
- 使用mybatis实现CRUD
- MyBATIS使用CRUD
- MyBatis实现CRUD操作
- mybatis 完整的CRUD
- mybatis的CRUD操作
- MyBatis的CRUD
- mybatis进行CRUD操作
- Mybatis实现CRUD实例
- Mybatis的CRUD操作
- MyBatis 的CRUD 功能
- MyBatis CRUD Demo
- mybatis的动态CRUD
- 题目四 ASCII码排序
- 转载:《史上最全最强SpringMVC详细示例实战教程》
- hdu3782xxx定律(位运算)
- hibernate查询数据库char类型字段时只返回一个字符
- 转载:mybatis入门
- mybatis CRUD
- NSTimer、CADisplayLink、GCD 三种定时器的用法
- ibatis的CURD
- GET和POST区别详解
- 杭电1114Piggy-Bank
- 正则表达式30分钟入门教程
- private、protected、default与public区别
- servlet学习---第一天
- eclipse 中git解决冲突