初见Mybatis之CRUD操作
MyBatis是一个半自动化映射的ORM框架,可以极大的简化访问数据库的操作,又不失灵活性,本文通过一个实例来介绍如何MyBatis进行增删改查操作。Mybatis进行数据库的CRUD操作主要分为三个步骤:
一丶CRUD操作基本流程
1.配置Mapper配置文件:Mapper文件用来设计CRUD的sql语句内容,以及输入参数和返回参数,这是Mybatis灵活性的体现,可自己优化复杂的sql语句性能,以及配置存储过程等。
2.配置MyBatis_config配置文件:这个配置文件是mybatis的主配置文件,用来配置和数据库的相关信息,在这个文件中需要引用Mapper配置文件。
3.Dao层的代码中,调用Mybatis提供的API,完成数据的操作。利用MyBatis提供的API访问数据库一般是如下流程:
读取Mybatis配置文件->创建SqlSessionFactory->创建SqlSession对象->指向sql语句。
二丶CRUD操作案例,通过一个对Customer表进行增删改查的案例,介绍Mybatis的CRUD操作。
图1 数据库中customer表的内容
1.customer对应表的实体对象设计:
/**
* customer对应POJO类
* @authorSmartTu
*/
public classCustomer {
publicint id;
publicString name;
publicString job;
publicString telephone;
publicint getId() {
returnid;
}
publicvoid setId(int id) {
this.id= id;
}
publicString getName() {
returnname;
}
publicvoid setName(String name) {
this.name= name;
}
publicString getJob() {
returnjob;
}
publicvoid setJob(String job) {
this.job= job;
}
publicString getTelePhone() {
returntelephone;
}
publicvoid setTelePhone(String telePhone){
this.telephone= telePhone;
}
@Override
publicString toString() {
return"Customer [id=" + id + ", name=" + name + ",job=" + job + ", telephone=" + telephone + "]";
}
}
2.Mybatis中Mapper映射文件配置,在本案例中这Mapper配置文件名是CustomerMapper,路径是com.bupt.customer
${sql}
insert intoCustomer(id,name,job,telephone) value(#{id},#{name},#{job},#{telephone});
update customer setname=#{name},job=#{job},telephone=#{telephone} where id=#{id}
delete from customer where id=#{id}
3.Mybatis的主配置文件,从主配置文件中,可以发现对数据库连接的相关内容进行了配置,并且引用了了先前配置Mapper对象(MyBatis主配置文件,应引用所有的Mapper文件)
4,Dao代码操作数据库,CustomerDaoImpl类实现对了对数据库的增删改查操作。
public classCustomerDaoImpl implementsCustomerDao{
/**
* 1.这里必须要强调一下,SqlSessionFactory对象是非常消耗资源的一个类
* 每一个数据库执需要new一个SqlSessionFactory对象即可
* 如果一个数据库对应多个SqlSessionFactory对象,那么数据库资源会被耗尽
* 2.在实际的开发中SqlSession对象应该设置为单例
* 3.在这个程序中为了简单起见,没有利用单例示范,但是实际开发中运用单例是必须的
* @throws IOException 获取SqlSession对象
*/
publicSqlSession getSqlSession() throwsIOException{
String configPath="mybatis_config.xml";
InputStream inputStream = Resources.getResourceAsStream(configPath);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession();
returnsqlSession;
}
/**
* @param customer待插入对象的实体类
*/
@Override
publicvoid insertCustomer(Customer customer)throws IOException {
// TODO Auto-generated method stub
String configPath="mybatis_config.xml";
InputStream inputStream = Resources.getResourceAsStream(configPath);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sessionFactory.openSession();
sqlSession.insert("com.bupt.mapper.CustomerMapper"+".insertCustomer",customer);
sqlSession.commit();
sqlSession.close();
}
/**
* 通过customer的id更新customer对象
* @param customer 新对象
*/
@Override
publicvoid update(Customer customer) throws IOException {
// TODO Auto-generated method stub
SqlSession sqlSession = getSqlSession();
sqlSession.update("com.bupt.mapper.CustomerMapper"+".updateCustomer",customer);
sqlSession.commit();
sqlSession.close();
}
/**
* 通过id删除指定对象
* @param id 待删除对象id
*/
@Override
publicvoid deleteByid(int id) throws IOException {
// TODO Auto-generated method stub
SqlSession sqlSession = getSqlSession();
sqlSession.update("com.bupt.mapper.CustomerMapper"+".deleteByid",id);
sqlSession.commit();
sqlSession.close();
}
/**
* @param id 精确查找对象的id
* @return Customer 通过id查询后的Customer对象
*/
@Override
publicCustomer queryByid(int id) throws IOException {
// TODO Auto-generated method stub
SqlSession sqlSession = getSqlSession();
Customer customer =sqlSession.selectOne("com.bupt.mapper.CustomerMapper"+".queryByid",id);
sqlSession.commit();
sqlSession.close();
returncustomer;
}
/**
* 利用名字进行模糊查询
* @param name 查询名字
* @return 满足条件的customer对象集合
*/
@Override
publicList queryByName(String name) throws IOException {
// TODO Auto-generated method stub
SqlSession sqlSession = getSqlSession();
List list =sqlSession.selectList("com.bupt.mapper.CustomerMapper"+".queryByName",name);
sqlSession.commit();
sqlSession.close();
returnlist;
}
}
5.测试代码,在测试过程中引入了Junit4单元测试框架
public classMainCustomer {
@Test
publicvoid insertTest(){
Customer customer = new Customer();
customer.id=3;
customer.name="SmartTu";
customer.job="student";
customer.telephone="1314";
CustomerDao customerDao = new CustomerDaoImpl();
try{
customerDao.insertCustomer(customer);
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
publicvoid updateTest(){
Customer customer = new Customer();
customer.id=1;
customer.name="SmartTuTu";
customer.job="student";
customer.telephone="1314";
CustomerDao customerDao = new CustomerDaoImpl();
try{
customerDao.update(customer);
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
publicvoid deleteTest(){
intid= 1;
CustomerDao customerDao = new CustomerDaoImpl();
try{
customerDao.deleteByid(id);;
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
publicvoid queryByidTest(){
intid= 1;
CustomerDao customerDao = new CustomerDaoImpl();
try{
Customer customer =customerDao.queryByid(id);
System.out.println(customer.toString());
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
publicvoid queryByNameTest(){
String name= "Tu";
CustomerDao customerDao = new CustomerDaoImpl();
try{
List list =customerDao.queryByName(name);
for(int i =0;i