1 抽取MyBatisUtil
其中的sessionFactory必须用同一个对象,不然会空指针异常!
public enum MyBatisUtil {
INSTANCE;
private static SqlSessionFactory sessionFactory = null;
static {
try {
sessionFactory = new SqlSessionFactoryBuilder().build(Resources
.getResourceAsStream("MyBatis-config.xml"));
} catch (IOException e) {
e.printStackTrace();
}
}
public SqlSession openSession() {
return sessionFactory.openSession();
}
}
2 提取db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcdemo?useSSL=false
usename=root
password=111111
3 配置类型别名
<?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>
<!-- 引入db.properties文件 -->
<properties resource="db.properties" />
<!-- 为类型起别名 -->
<typeAliases>
<typeAlias type="cn.itsource.shopping.domain.Product" alias="Product" />
</typeAliases>
<!-- 环境配置 -->
<environments default="development">
<!-- 连接数据的基本信息 -->
<environment id="development">
<!-- 事务管理器:JDBC的管理机制 -->
<transactionManager type="JDBC" />
<!-- 配置连接池(数据源) -->
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${usename}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<!-- 关联映射文件 -->
<mappers>
<mapper resource="cn\itsource\shopping\domain\ProductMapper.xml" />
</mappers>
</configuration>
4 列名和属性名不同
当属性名和数据库中的列名不同的时候,可以使用resultMap设置property=”字段名” column=”列名”其中的数据库中的名称不分大小写,字段中的名称严格区分大小写!
<?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">
<!-- 映射Product对象和对应表关系的,操作该表/对象的SQL全部都写在这里 -->
<mapper namespace="cn.itsource.shopping.mapper.ProductMapper">
<!-- 里面写SQL -->
<!--
id:唯一的标识,和namespace组成全局的唯一名称
cn.itsource.shopping.mapper.ProductMapper.list
parameterType:方法的参数类型
resultType:返回类型,表中一行记录对应的对象
-->
<!-- 查询所有 -->
<select id="list" resultMap="productMapping">
SELECT * FROM product
</select>
<!-- 查询单个 -->
<!-- 里面的参数为什么用小long:因为基本类型的别名前面都是小写 -->
<select id="get" parameterType="long" resultType="Product">
SELECT * FROM product where id = #{id}
</select>
<!-- 插入操作 -->
<insert id="save" parameterType="Product" useGeneratedKeys="true" keyProperty="id">
insert into product (productName,brand,supplier,salePrice,costPrice,cutoff,dir_id)
values(#{productName},#{brand},#{supplier},#{salePrice},#{costPrice},#{cutoff},#{dir_id})
</insert>
<!-- 修改操作 -->
<update id="update" parameterType="Product">
UPDATE product SET productName = #{productName},brand = #{brand},supplier = #{supplier},
salePrice = #{salePrice},costPrice = #{costPrice},cutoff = #{cutoff},dir_id = #{dir_id}
WHERE id = #{id}
</update>
<!-- 删除操作 -->
<delete id="delete" parameterType="long">
delete from product where id = #{id}
</delete>
<!-- 解决属性名列名不同的问题 -->
<!-- 结果映射 -->
<resultMap type="Product" id="productMapping">
<!-- 映射主键列 -->
<id property="id" column="id"/>
<!-- 映射非主键列 -->
<result property="productName" column="productName"/>
</resultMap>
</mapper>
DAO
public class ProductDAOImpl implements IProductDAO {
public void save(Product pro) {
SqlSession session = MyBatisUtil.INSTANCE.openSession();
try {
session.insert("cn.itsource.shopping.mapper.ProductMapper.save", pro);
session.commit();
} finally {
session.close();
}
}
public void delete(Long id) {
SqlSession session = MyBatisUtil.INSTANCE.openSession();
try {
session.update("cn.itsource.shopping.mapper.ProductMapper.delete", id);
session.commit();
} finally {
session.close();
}
}
public void update(Product pro) {
SqlSession session = MyBatisUtil.INSTANCE.openSession();
try {
session.update("cn.itsource.shopping.mapper.ProductMapper.update", pro);
session.commit();
} finally {
session.close();
}
}
public Product get(Long id) {
SqlSession session = MyBatisUtil.INSTANCE.openSession();
try {
return session.selectOne("cn.itsource.shopping.mapper.ProductMapper.get", id);
} finally {
session.close();
}
}
public List<Product> list() {
SqlSession session = MyBatisUtil.INSTANCE.openSession();
try {
return session.selectList("cn.itsource.shopping.mapper.ProductMapper.list");
} finally {
session.close();
}
}
DAO的实现接口
import java.util.List;
import cn.itsource.shopping.domain.Product;
public interface IProductDAO {
void save(Product pro);
void delete(Long id);
void update(Product pro);//long id 包装进去product
Product get(Long id);
List<Product> list();
}
测试类
private IProductDAO dao = new ProductDAOImpl();
@Test
public void testSave() {
Product pro = new Product();
pro.setProductName("iphone9s");
pro.setBrand("apple");
pro.setSupplier("苹果公司");
pro.setSalePrice(new BigDecimal("7000"));
pro.setCostPrice(new BigDecimal("2000"));
pro.setCutoff(0.9);
pro.setDir_id(3L);
//pro.setId(12L);
dao.save(pro);
System.out.println(pro);
}
@Test
public void testDelete() {
dao.delete(24L);
}
@Test
public void testUpdate() {
Product pro = new Product();
pro.setProductName("iphone5s");
pro.setBrand("apple9s");
pro.setSupplier("苹果公司2");
pro.setSalePrice(new BigDecimal("6000"));
pro.setCostPrice(new BigDecimal("1000"));
pro.setCutoff(0.8);
pro.setDir_id(5L);
pro.setId(25L);
dao.update(pro);
}
@Test
public void testGet() {
Product pro = dao.get(25L);
System.out.println(pro);
}
@Test
public void testList() {
List<Product> list = dao.list();
for (Product p : list) {
System.out.println(p);
}
}
商品类对象
public class Product {
private Long id;
private String productName;
private String brand;
private String supplier;
private BigDecimal salePrice;
private BigDecimal costPrice;
private Double cutoff;
private Long dir_id;//分类编号
public Long getId() {
return id;
}
public String getProductName() {
return productName;
}
public String getBrand() {
return brand;
}
public String getSupplier() {
return supplier;
}
public BigDecimal getSalePrice() {
return salePrice;
}
public BigDecimal getCostPrice() {
return costPrice;
}
public Double getCutoff() {
return cutoff;
}
public Long getDir_id() {
return dir_id;
}
public void setId(Long id) {
this.id = id;
}
public void setProductName(String productName) {
this.productName = productName;
}
public void setBrand(String brand) {
this.brand = brand;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
public void setSalePrice(BigDecimal salePrice) {
this.salePrice = salePrice;
}
public void setCostPrice(BigDecimal costPrice) {
this.costPrice = costPrice;
}
public void setCutoff(Double cutoff) {
this.cutoff = cutoff;
}
public void setDir_id(Long dir_id) {
this.dir_id = dir_id;
}
public String toString() {
return "Product [id=" + id + ", productName=" + productName + ", brand=" + brand + ", suppliet=" + supplier
+ ", salePrice=" + salePrice + ", costPrice=" + costPrice + ", cutoff=" + cutoff + ", dir_id=" + dir_id
+ "]";
}