IDEA项目搭建四——使用Mybatis实现Dao层
生活随笔
收集整理的這篇文章主要介紹了
IDEA项目搭建四——使用Mybatis实现Dao层
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、引入mybatis及mysql的jar包
可以從阿里云上面查找版本,db操作放在dao層所以打開該層的pom.xml文件,找到<dependencies>節(jié)點增加兩個引入
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version> </dependency> <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.45</version> </dependency>保存后系統(tǒng)會自動下載對應版本的jar包,我們開始編碼
?
二、配置mybatis(手動創(chuàng)建)
1.在dao層的src/main下創(chuàng)建和java文件夾同級目錄的resources文件夾,它默認會變換類型,如果不變則手動調(diào)整一下
2.在resources文件夾下創(chuàng)建mysql.properties文件
填入mysql數(shù)據(jù)庫連接信息
jdbc.driver=com.mysql.jdbc.Driver#數(shù)據(jù)庫連接允許中文需要指明編碼方式
jdbc.url=jdbc:mysql://10.11.12.237:3306/tyh_test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
3.在resources文件夾下創(chuàng)建mybatis_cfg.xml文件
填入mybatis配置信息
<?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><!-- 引入配置文件 --><properties resource="mysql.properties"></properties><!-- 為Java實體設置類別名 --><typeAliases><!-- 設置方式1,一個一個配置 type中放置的是類的全路徑,alias中放置的是 類別名<typeAlias type="com.tyh.entity.UserEntity" alias="UserEntity"/> --><!-- 設置方式2,自動掃描,將Java類的類名作為類的 類別名 --><package name="com.tyh.entity"/></typeAliases><!-- 配置mybatis運行環(huán)境 --><environments default="dev"><environment id="dev"><!-- 代表使用JDBC的提交和回滾來管理事務 --><transactionManager type="JDBC"/><!-- mybatis提供了3種數(shù)據(jù)源類型,分別是:POOLED,UNPOOLED,JNDI --><!-- POOLED 表示支持JDBC數(shù)據(jù)源連接池 --><!-- UNPOOLED 表示不支持數(shù)據(jù)源連接池 --><!-- JNDI 表示支持外部數(shù)據(jù)源連接池 --><dataSource type="POOLED"><!-- ${jdbc.driver}代表配置文件中的某一項的key --><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><!-- 為mybatis的映射文件mapper.xml設置路徑 --><mappers><!-- 映射方式1,一個一個設置<mapper resource="com.tyh.dao.mapper.UserMapper.xml"/> --><!-- 映射方式2,自動掃描包內(nèi)的Mapper接口與配置文件 --><package name="com/tyh/dao/mapper"/></mappers></configuration>?4.在src/main/java下創(chuàng)建各自的包,我這里是com.tyh.dao.mapper,在mapper文件夾下創(chuàng)建UserMapper的接口文件,用于編寫DB操作函數(shù)
public interface UserMapper {/*** 添加用戶* @param entity 實體* @return 添加id* @throws Exception*/int add(UserEntity entity) throws Exception;int delete(int id) throws Exception;int update(UserEntity entity) throws Exception;UserEntity get(int id) throws Exception;List<UserEntity> list() throws Exception; }?
5.同樣在mapper文件夾下創(chuàng)建UserMapper.xml文件,用于編寫與接口函數(shù)對應的SQL腳本,此處切記節(jié)點屬性不要寫錯,否則會報錯
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- cache 配置給定命名空間的緩存 cache-ref 從其他命名空間引用緩存配置 resultType 返回值類型 resultMap 描述如何從數(shù)據(jù)庫結果集中裝載你的對象 parameterType 參數(shù)類型 parameterMap 已過時 sql 可重用的SQL語句塊 insert 插入語句 update 更新語句 delete 刪除語句 select 查詢語句 --><!-- 指明當前xml對應的Mapper --> <mapper namespace="com.tyh.dao.mapper.UserMapper"><!-- 自定義返回結果集 如果實體屬性名與列名一致則不需要此部分,若不一致則需要 --><!--<resultMap id="userMap" type="UserBean">--><!--<id property="id" column="id" javaType="java.lang.Integer"></id>--><!--<result property="username" column="username" javaType="java.lang.String"></result>--><!--<result property="password" column="password" javaType="java.lang.String"></result>--><!--<result property="account" column="account" javaType="java.lang.Double"></result>--><!--</resultMap>--><!-- 各種標簽中的id屬性與mapper接口中的方法名一一對應,id屬性必須唯一不能重復使用,parameterType屬性指明查詢時使用的參數(shù)類型,resultType屬性指明查詢返回的結果集類型 --><!-- #{}中的內(nèi)容,為占位符,當參數(shù)為某個Entity時,表示放置該Entity對象的屬性值 --><!-- useGeneratedKeys:(僅對insert有用)這會告訴MyBatis使用JDBC的getGeneratedKeys方法來取出由數(shù)據(jù)(比如:像 MySQL 和 SQLServer 這樣的數(shù)據(jù)庫管理系統(tǒng)的自動遞增字段)內(nèi)部生成的主鍵。默認值: false。 --><!-- keyProperty:(僅對 insert有用)標記一個屬性, MyBatis 會通過 getGeneratedKeys或者通過 insert 語句的 selectKey 子元素設置它的值。默認:不設置。 --><insert id="add" useGeneratedKeys="true" keyProperty="id">insert into user (username, password, age) values (#{userName},#{password},#{age});</insert><delete id="delete" parameterType="int">delete from user where id=#{id}</delete><update id="update" >update user set username=#{username}, password=#{password}, age=#{age} where id=#{id};</update><!-- select節(jié)點必須有resultType屬性如果不是自定義結果集就可以直接寫實體包名[要含包名的完整類名] --><select id="get" resultType="com.tyh.entity.UserEntity">select * from user where id=#{id};</select><select id="list" resultType="com.tyh.entity.UserEntity">select * from user;</select> </mapper>?
6.我們在文件夾內(nèi)添加的xml及properties文件默認編譯不會被復制過去,所以運行時會提示找不到文件,在配置中指明要一起打包文件即可
我這個項目有parent模塊,所以在父模塊中添加配置,子模塊會自動繼承,如果沒有父模塊則單獨在demo-dao層的pom.xml文件添加也可
<!-- build節(jié)點普遍已經(jīng)存在了,在其下增加resources等節(jié)點 --> <build><!-- 打包文件內(nèi)容配置 --><resources><!-- 將src/main/java下的**/*.xml任意目錄下的xml文件打包到對應的文件目錄中 --><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource><!-- 將src/main/resources下的**/*.*任意目錄下的任意文件打包到對應的文件目錄中 --><resource><directory>src/main/resources</directory><includes><include>**/*.*</include></includes></resource></resources> </build>?
7.基礎已經(jīng)準備好了,下面創(chuàng)建數(shù)據(jù)庫Mybatis操作對象,在com.tyh.dao下創(chuàng)建DBTools數(shù)據(jù)庫工具類
public class DBTools {public static SqlSessionFactory sessionFactory;static {try {//使用MyBatis提供的Resources類加載mybatis的配置文件Reader reader = Resources.getResourceAsReader("mybatis_cfg.xml");//構建sqlSession的工廠sessionFactory = new SqlSessionFactoryBuilder().build(reader);} catch (Exception e) {e.printStackTrace();}}//創(chuàng)建能執(zhí)行映射文件中sql的sqlSessionpublic static SqlSession getSqlSession(){return sessionFactory.openSession();} }?
8.編寫dao操作層,用于調(diào)用底層實現(xiàn)函數(shù)
public class UserDao {private SqlSession sqlSession;private UserMapper mapper;public UserDao() {sqlSession = DBTools.getSqlSession();mapper = sqlSession.getMapper(UserMapper.class);}public int add(UserEntity entity) throws Exception {//調(diào)用數(shù)據(jù)庫操作函數(shù)后需要commit才會提交int result = mapper.add(entity);sqlSession.commit();return result;}public int delete(int id) throws Exception {int result = mapper.delete(id);sqlSession.commit();return result;}public int update(UserEntity entity) throws Exception {int result = mapper.update(entity);sqlSession.commit();return result;}public UserEntity get(int id) throws Exception {UserEntity result = mapper.get(id);sqlSession.commit();return result;}public List<UserEntity> list() throws Exception {List<UserEntity> result = mapper.list();sqlSession.commit();return result;} }?
至此Dao層的DB操作已經(jīng)完成,自己編寫service和web調(diào)用即可,以下是我項目的結構。
?
注:數(shù)據(jù)庫創(chuàng)建時也需要指明utf8格式編碼,否則會出現(xiàn)中文亂碼問題?
create database test charset utf8;?
轉載于:https://www.cnblogs.com/taiyonghai/p/9146701.html
總結
以上是生活随笔為你收集整理的IDEA项目搭建四——使用Mybatis实现Dao层的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 世界上最贵的鱼排名图片(全球最贵的鱼类排
- 下一篇: org.springframework.