MyBatis使用心得
生活随笔
收集整理的這篇文章主要介紹了
MyBatis使用心得
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
MyBatis框架
??作為操作數據庫的框架,相對于JPA來說,稍微要麻煩許多,因為需要自己寫Sql查詢語句。不過在國內使用率更高,因為它上手簡單,性能更高,因為自己寫sql,效率幾乎等同于底層jdbc,但是開發效率對比起Jpa來說就要低很多了,畢竟寫sql是一件很痛苦的事情。
??Jpa作為ORM的規范,我使用的是hibernate對它的實現,可以替我們準備好很多查詢方法,幾乎不用寫sql,開發效率極高,但是運行效率相對于MyBatis就要低許多了,而且上手程度要高很多,沒有MyBatis簡單。
使用MyBatis
導包
asm-3.3.1.jar cglib-2.2.2.jar commons-logging-1.1.1.jar javassist-3.17.1-GA.jar log4j-1.2.17.jar mybatis-3.2.1.jar mysql-connector-java-5.1.26-bin.jar slf4j-api-1.7.2.jar slf4j-log4j12-1.7.2.jar配置MyBatis-config.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><!--引入配置文件,用resource--><properties resource="jdbc.properties"></properties><!--取別名,使后面傳對象可以不用寫完全限定名,type是我們的全限定名,alias是我們取的別名,它是不區分大小寫的可以直接開啟某個包的別名使用,名字就是類名--><typeAliases><!--<typeAlias type="cn.itsource.domain.Product" alias="product"></typeAlias>--><package name="cn.itsource.domain"></package></typeAliases><!--環境門,可能有很多個,默認選中一個--><environments default="development"><!--開發環境--><environment id="development"><!--事物 選擇JDBC--><transactionManager type="JDBC"/><!--配置四大金剛--><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></dataSource></environment></environments><!--引入我們寫的sql配置文件,精確找到要查詢那個類,記得看路徑,還有后綴等問題--><mappers><mapper resource="cn/itsource/domain/ProductMapper.xml"/></mappers> </configuration>創建Domain,然后創建一個類,并配置XxxMapper.xml
package cn.itsource.domain;public class Product {private Long id;private String productName;private Double salePrice;private String supplier;private String brand;private Double cutoff;private Double costPrice;private Long dirId;public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getProductName() {return productName;}public void setProductName(String productName) {this.productName = productName;}public Double getSalePrice() {return salePrice;}public void setSalePrice(Double salePrice) {this.salePrice = salePrice;}public String getSupplier() {return supplier;}public void setSupplier(String supplier) {this.supplier = supplier;}public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}public Double getCutoff() {return cutoff;}public void setCutoff(Double cutoff) {this.cutoff = cutoff;}public Double getCostPrice() {return costPrice;}public void setCostPrice(Double costPrice) {this.costPrice = costPrice;}public Long getDirId() {return dirId;}public void setDirId(Long dirId) {this.dirId = dirId;}@Overridepublic String toString() {return "Product{" +"id=" + id +", productName='" + productName + '\'' +", salePrice=" + salePrice +", supplier='" + supplier + '\'' +", brand='" + brand + '\'' +", cutoff=" + cutoff +", costPrice=" + costPrice +", dirId=" + dirId +'}';} } <?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,命名,完全限定名,然后再通過查詢的id來精確定位要調用哪個方法--> <mapper namespace="cn.itsource.domain.Product"><!--當前類跟數據庫里字段對應不上時配置這個,下面的返回result記得換成Map設置主鍵跟類一致--><resultMap id="ProductMap" type="Product"><id column="id" property="id" /><result column="dir_id" property="dirId" /></resultMap><!--parameterType傳入的類型,不同的類型 有專門寫好的 名字,參考文檔里面,尤其要注意這里resultType:返回的類型 就是一條該類的數據,不是指返回List什么的--><select id="findOne" parameterType="long" resultMap="ProductMap">select * from product where id = #{id}</select><!--查詢全部不需要傳參 ,返回的還是該類的一條數據--><select id="findAll" resultMap="ProductMap">select * from product</select><!--是否開啟主鍵調用,數據庫里的id 對應 我們類里面的id--><insert id="save" parameterType="cn.itsource.domain.Product"useGeneratedKeys="true" keyColumn="id" keyProperty="id">insert into product(productName,dir_id,salePrice,supplier,brand,cutoff,costPrice)values (#{productName},#{dirId},#{salePrice},#{supplier},#{brand},#{cutoff},#{costPrice})</insert><update id="update" parameterType="cn.itsource.domain.Product" >update product set productName=#{productName},dir_id=#{dirId},salePrice=#{salePrice},supplier=#{supplier},brand=#{brand},cutoff=#{cutoff},costPrice=#{costPrice} where id = #{id}</update><delete id="delete" parameterType="long">delete from product where id = #{id}</delete><!--$和#的區別$需要的是對象,里面裝的是這個對象的屬性 $是直接拼接字符串,需要自己加""#使用的是占位符(預編譯模式) 預編譯性能更好,更安全,防止sql注入--><select id="findOne2" parameterType="cn.itsource.domain.ProductQuery" resultMap="ProductMap">select * from product where productName = "${name}"</select> </mapper>然后就可以開始測試了
public class MyBatisTest {@Testpublic void testFindOne() throws Exception {//通過數據源來獲取我們的核心配置文件,記得選擇ibatis的包Reader reader = Resources.getResourceAsReader("mybatis-config.xml");//然后通過sql會話工廠創建對象來創建工廠對象,傳入我們的核心讀取對象,記得要new出來SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);//打開會話,獲取sqlsession對象SqlSession session = factory.openSession();//然后就可以調取查詢方法了,前面傳入精準定位的路徑和需要查詢的id,然后傳入參數Product product = session.selectOne("cn.itsource.domain.Product.findOne", 1L);System.out.println(product);//關閉流session.close();}}將獲取sqlsession的代碼抽取成工具類
package cn.itsource.util;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 java.io.IOException;public class MybatisUtil {private static SqlSessionFactory sessionFactory;static {try {sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));} catch (Exception e) {e.printStackTrace();}}public static SqlSession openSession(){return sessionFactory.openSession();} }然后完成Dao層,Impl層
package cn.itsource.dao;import cn.itsource.domain.Product;import java.util.List;public interface IProductDao {void save(Product product);void update(Product product);void delete(Long id);Product findOne(Long id);List<Product> findAll(); } package cn.itsource.dao.impl;import cn.itsource.dao.IProductDao; import cn.itsource.domain.Product; import cn.itsource.util.MybatisUtil; import org.apache.ibatis.session.SqlSession;import java.util.List;public class ProductDaoImpl implements IProductDao {@Overridepublic void save(Product product) {SqlSession session = null;try {session = MybatisUtil.openSession();session.insert("cn.itsource.domain.Product.save",product);session.commit();} catch (Exception e) {session.rollback();e.printStackTrace();} finally {session.close();}}@Overridepublic void update(Product product) {SqlSession session = null;try {session = MybatisUtil.openSession();session.update("cn.itsource.domain.Product.update",product);session.commit();} catch (Exception e) {session.rollback();e.printStackTrace();} finally {session.close();}}@Overridepublic void delete(Long id) {SqlSession session = null;try {session = MybatisUtil.openSession();session.delete("cn.itsource.domain.Product.delete",id);session.commit();} catch (Exception e) {session.rollback();e.printStackTrace();} finally {session.close();}}@Overridepublic Product findOne(Long id) {SqlSession session = null;try {session = MybatisUtil.openSession();return session.selectOne("cn.itsource.domain.Product.findOne",id);} catch (Exception e) {e.printStackTrace();} finally {session.close();}return null;}@Overridepublic List<Product> findAll() {SqlSession session = null;try {session = MybatisUtil.openSession();return session.selectList("cn.itsource.domain.Product.findAll");} catch (Exception e) {e.printStackTrace();} finally {session.close();}return null;} }最后測試所有方法
package cn.itsource.test;import cn.itsource.dao.IProductDao; import cn.itsource.dao.impl.ProductDaoImpl; import cn.itsource.domain.Product; import org.junit.Test;public class ProductDaoImplTest {IProductDao iProductDao = new ProductDaoImpl();@Testpublic void save() {Product product = iProductDao.findOne(1L);product.setId(null);product.setProductName("雷蛇曼巴蛇");iProductDao.save(product);System.out.println(product);}@Testpublic void update() {Product product = iProductDao.findOne(21L);product.setProductName("憨憨牌鼠標");iProductDao.update(product);}@Testpublic void delete() {iProductDao.delete(25L);}@Testpublic void findOne() {Product product = iProductDao.findOne(1L);System.out.println(product);}@Testpublic void findAll() {iProductDao.findAll().forEach(p-> System.out.println(p));} }總結
以上是生活随笔為你收集整理的MyBatis使用心得的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 论文阅读:Tube Convolutio
- 下一篇: 15款免费艺术院校学生求职简历word模