一、引入mybatis及mysql的jar包
可以從阿里雲上面查找版本,db操作放在dao層所以打開該層的pom.xml文件,找到<dependencies>節點增加兩個引入
<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>
保存后系統會自動下載對應版本的jar包,我們開始編碼
二、配置mybatis(手動創建)
1.在dao層的src/main下創建和java文件夾同級目錄的resources文件夾,它默認會變換類型,如果不變則手動調整一下
2.在resources文件夾下創建mysql.properties文件
填入mysql數據庫連接信息
jdbc.driver=com.mysql.jdbc.Driver
#數據庫連接允許中文需要指明編碼方式
jdbc.url=jdbc:mysql://10.11.12.237:3306/tyh_test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
3.在resources文件夾下創建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運行環境 --> <environments default="dev"> <environment id="dev"> <!-- 代表使用JDBC的提交和回滾來管理事務 --> <transactionManager type="JDBC"/> <!-- mybatis提供了3種數據源類型,分別是:POOLED,UNPOOLED,JNDI --> <!-- POOLED 表示支持JDBC數據源連接池 --> <!-- UNPOOLED 表示不支持數據源連接池 --> <!-- JNDI 表示支持外部數據源連接池 --> <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,自動掃描包內的Mapper接口與配置文件 --> <package name="com/tyh/dao/mapper"/> </mappers> </configuration>
4.在src/main/java下創建各自的包,我這里是com.tyh.dao.mapper,在mapper文件夾下創建UserMapper的接口文件,用於編寫DB操作函數
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文件夾下創建UserMapper.xml文件,用於編寫與接口函數對應的SQL腳本,此處切記節點屬性不要寫錯,否則會報錯
<?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 描述如何從數據庫結果集中裝載你的對象 parameterType 參數類型 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屬性指明查詢時使用的參數類型,resultType屬性指明查詢返回的結果集類型 --> <!-- #{}中的內容,為占位符,當參數為某個Entity時,表示放置該Entity對象的屬性值 --> <!-- useGeneratedKeys:(僅對insert有用)這會告訴MyBatis使用JDBC的getGeneratedKeys方法來取出由數據(比如:像 MySQL 和 SQLServer 這樣的數據庫管理系統的自動遞增字段)內部生成的主鍵。默認值: 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節點必須有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.我們在文件夾內添加的xml及properties文件默認編譯不會被復制過去,所以運行時會提示找不到文件,在配置中指明要一起打包文件即可
我這個項目有parent模塊,所以在父模塊中添加配置,子模塊會自動繼承,如果沒有父模塊則單獨在demo-dao層的pom.xml文件添加也可
<!-- build節點普遍已經存在了,在其下增加resources等節點 --> <build> <!-- 打包文件內容配置 --> <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.基礎已經准備好了,下面創建數據庫Mybatis操作對象,在com.tyh.dao下創建DBTools數據庫工具類
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(); } } //創建能執行映射文件中sql的sqlSession public static SqlSession getSqlSession(){ return sessionFactory.openSession(); } }
8.編寫dao操作層,用於調用底層實現函數
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 { //調用數據庫操作函數后需要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操作已經完成,自己編寫service和web調用即可,以下是我項目的結構。
注:數據庫創建時也需要指明utf8格式編碼,否則會出現中文亂碼問題
create database test charset utf8;