SSM框架:Spring+SpringMVC+MyBatis
今天记录下其中的MyBatis,这是持久化层,说白了就是将原来的JDBC封装抽取出来更加灵活简单易用的框架。
MyBatis:yBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。
今天记录下其中的MyBatis,这是持久化层,说白了就是将原来的JDBC封装抽取出来更加灵活简单易用的框架。
MyBatis:yBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。MyBatis是一个优秀的持久层框架,它对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。Mybatis通过xml或注解的方式将要执行的各种statement(statement、preparedStatemnt、CallableStatement)配置起来,并通过java对象和statement中的sql进行映射生成最终执行的sql语句,最后由mybatis框架执行sql并将结果映射成java对象并返回。
下面的例子是用MyBatis实现的对product表的基本增删改查操作,可以帮助理解使用框架和单独使用jdbc有什么不同和优缺点。
beans包下面的Product类:
package cn.edu360.beans;
public class Product {
private long id;
private String name;
private float price;
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
}
public Product() {
super();
}
public Product(int id, String name, float price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
Product的dao层实现方法:
package cn.edu360.dao;
import java.io.IOException;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import cn.edu360.beans.Product;
/**
* DAO : Database Access Object 操作Product数据库的增删改查方法
*
* @author Administrator
*
*/
public class ProductDaoImpl {
/**
* 创建SQLSessionFactory使用的是单例模式,相当于连接池
*/
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("SqlMapConfig.xml"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 向数据库插入一条Product数据
*/
public void save(Product product) {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.insert("product.save", product);
sqlSession.commit();
sqlSession.close();
}
/**
* 根据id删除相关数据信息
*
* @param id
*/
public void deleteById(long id) {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.delete("product.deleteById", id);
sqlSession.commit();
sqlSession.close();
}
/**
* 根据传进来的product各项属性更新数据库
*
* @param product
*/
public void update(Product product) {
SqlSession sqlSession = sqlSessionFactory.openSession();
sqlSession.update("product.update", product);
sqlSession.commit();
sqlSession.close();
}
/**
* 查找所有的Product信息,返回为List类型
*
* @return
*/
public List<Product> findAll() {
SqlSession sqlSession = sqlSessionFactory.openSession();
List<Product> selectList = sqlSession.selectList("product.findProduct");
sqlSession.close();
return selectList;
}
/**
* 根据id值查找数据库返回一个Product对象
*
* @param id
* @return
*/
public Product getById(long id) {
SqlSession sqlSession = sqlSessionFactory.openSession();
Product selectOne = sqlSession.selectOne("product.getById", id);
sqlSession.close();
return selectOne;
}
}
核心配置文件
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="12580" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mappers/Product.xml"/>
</mappers>
</configuration>
子配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="product">
<select id="findProduct" resultType="cn.edu360.beans.Product">
select * from product
</select>
<insert id="save" parameterType="cn.edu360.beans.Product">
insert into product (name,price) values (#{name},#{price})
</insert>
<delete id="deleteById" parameterType="long">
delete from product where id = #{id}
</delete>
<update id="update" parameterType="cn.edu360.beans.Product">
update product set name=#{name},price=#{price} where id = #{id}
</update>
<select id="getById" parameterType="long" resultType="cn.edu360.beans.Product">
select * from product where id = #{id}
</select>
</mapper>
JUnit测试方法:
package cn.edu360.dao;
import java.util.List;
import org.junit.Test;
import cn.edu360.beans.Product;
public class ProductDaoImplTest {
@Test
public void testSave() {
ProductDaoImpl productDaoImpl = new ProductDaoImpl();
Product product = new Product();
product.setName("音乐");
product.setPrice(19);
productDaoImpl.save(product);
}
@Test
public void testDeleteById() {
ProductDaoImpl productDaoImpl = new ProductDaoImpl();
productDaoImpl.deleteById(1L);
}
@Test
public void testUpdate() {
ProductDaoImpl productDaoImpl = new ProductDaoImpl();
Product product = new Product();
product.setId(1);
product.setName("生物");
product.setPrice(19);
productDaoImpl.update(product);
}
@Test
public void testFindAll() {
ProductDaoImpl productDaoImpl = new ProductDaoImpl();
List<Product> productList = productDaoImpl.findAll();
for (Product product : productList) {
System.out.println(product);
}
}
@Test
public void testGetById() {
ProductDaoImpl productDaoImpl = new ProductDaoImpl();
Product product = productDaoImpl.getById(5L);
System.out.println(product);
}
}
其实基本的增删改查实现很简单,较之前的JDBC更加易于优化,将需要配置的信息抽取到xml配置文件中,便于后期的优化和维护。