單獨使用MyBatis的簡單示例:
mybaties-config.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> <typeAliases><!-- 別名 --> <typeAlias alias="role" type="com.xc.pojo.Role"/> </typeAliases> <!-- 數據庫環境 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/springmvc?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect=true"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <!-- 映射文件 --> <mappers> <mapper resource="mapper/RoleMapper.xml"/> </mappers> </configuration>
Role.java:
POJO對象
構造一個POJO對象。最終查詢會映射到它上面,或者將其保存到數據庫中。
package com.xc.pojo; public class Role { //CREATE TABLE `t_role` ( // `id` int(12) NOT NULL AUTO_INCREMENT, // `role_name` varchar(60) NOT NULL, // `note` varchar(512) DEFAULT NULL, // PRIMARY KEY (`id`) // ) private Long id; private String roleName; private String note; //get...set... }
RoleMapper.java:
映射器接口
其中,insertRole代表插入一個Role對象;deleteRole則是刪除;updateRole是修改一個Role對象;getRole是獲取一個Role對象;findRoles則是通過角色名稱獲得一個角色對象列表。
package com.xc.mapper; import com.xc.pojo.Role; import org.apache.ibatis.annotations.Select; import java.util.List; public interface RoleMapper { public Role getRole(Long id); @Select("select id, role_name as roleName, note from t_role where id=#{id}") public Role getRole2(Long id); public int insertRole(Role role); public int deleteRole(Long id); public int updateRole(Role role); public List<Role> findRoles(String roleName); }
RoleMapper.xml:
映射器XML文件,描述映射關系,SQL等內容
這是一些比較簡單的SQL語句,insert、delete、select、update元素代表了增、刪、查、改,而它們里面的元素id則標識了對應的SQL。parameterType標出了是什么類型的參數,re-sultType則代表結果映射成為什么類型。其中insert、delete和update返回的都是影響條數。
<?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="com.xc.mapper.RoleMapper"> <insert id="insertRole" parameterType="role">
insert into t_role(role_name, note) values(#{roleName}, #{note}) </insert> <delete id="deleteRole" parameterType="long">
delete from t_role where id= #{id} </delete> <update id="updateRole" parameterType="role">
update t_role set role_name = #{roleName}, note = #{note} where id= #{id} </update> <select id="getRole" parameterType="long" resultType="role">
select id, role_name as roleName, note from t_role where id = #{id} </select> <select id="findRoles" parameterType="string" resultType="role">
select id, role_name as roleName, note from t_role where role_name like concat('%', #{roleName}, '%') </select> </mapper>
Chapter3Main測試類:
程序入口,擁有main方法
import com.xc.mapper.RoleMapper; import com.xc.pojo.Role; 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; import java.io.InputStream; public class test { public static void main(String[] args) { String resource = "mybatis-config.xml"; try { InputStream inputStream = Resources.getResourceAsStream(resource); //SqlSessionFactoryBuilder(構造器):它會根據配置或者代碼來生成SqlSessionFactory,采用的是分步構建的Builder模式。 //SqlSessionFactory(工廠接口):依靠它來生成SqlSession,使用的是工廠模式。 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //SqlSession(會話):一個既可以發送SQL執行返回結果,也可以獲取Mapper的接口。在現有的技術中,一般我們會讓其在業務邏輯代碼中“消失”,而使用的是MyBatis提供的SQL Mapper接口編程技術,它能提高代碼的可讀性和可維護性。 SqlSession sqlSession = sqlSessionFactory.openSession(); //SQL Mapper(映射器):MyBatis新設計存在的組件,它由一個Java接口和XML文件(或注解)構成,需要給出對應的SQL和映射規則。它負責發送SQL去執行,並返回結果。 RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class); Role role = roleMapper.getRole(1L); System.out.println(role.toString()); Role role2 = roleMapper.getRole2(1L); System.out.println(role2.toString()); } catch (IOException e) { e.printStackTrace(); } } }
Chapter3Main2測試類:
package com.xc.main; import com.xc.mapper.RoleMapper; import com.xc.pojo.Role; import com.xc.util.SqlSessionFactoryUtils; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; public class Chapter3Main2 { // Logger log = Logger.getLogger(Chapter3Main.class); private static Logger log = Logger.getLogger(Chapter3Main2.class); public static void main(String[] args) { SqlSession sqlSession = null; try { sqlSession = SqlSessionFactoryUtils.openSqlSession(); //通過SqlSession獲取了一個RoleMapper接口對象 RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class); //通過getRole方法獲取對象 Role role = roleMapper.getRole(1L); log.info(role.getRoleName()); } finally { if (sqlSession != null) { //正確關閉SqlSession對象 sqlSession.close(); } } } }
SqlSessionFactoryUtils.java:
package com.xc.util; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; /** * 使用mybatis-config.xml文件,通過SQLSessionFactory-Builder來構建SqlSessionFactory。由於SqlSessionFactory應該采用單例模式,所以這里使用單例模式去構建它 */ public class SqlSessionFactoryUtils { private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class; private static SqlSessionFactory SqlSessionFactory = null; //構造方法中加入了private關鍵字,使得其他代碼不能通過new的方式來創建它。 private SqlSessionFactoryUtils() { } public static SqlSessionFactory getSqlSessionFactory() { //加入synchronized關鍵字加鎖,主要是為了防止在多線程中多次實例化SqlSessionFactory對象,從而保證SqlSessionFactory的唯一性。 synchronized (LOCK) { if (SqlSessionFactory != null) { return SqlSessionFactory; } String resource = "mybatis-config.xml"; InputStream inputStream; try { inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); return null; } return SqlSessionFactory; } } //openSqlSession方法的作用則是創建SqlSession對象。 public static SqlSession openSqlSession() { if (SqlSessionFactory == null) { getSqlSessionFactory(); } return SqlSessionFactory.openSession(); } }
log4j.properties
通過logj4.properties文件配置,讓MyBatis打印了其運行過程的軌跡。我們可以清晰地看到了日志打印出來的SQL、SQL參數,以及返回的結果數,這樣有利於監控MyBatis的運行過程和定位問題的所在。
log4j.rootLogger=DEBUG,stdout log4j.logger.org.mybatis=DEBUG log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
附:
pom.xml
<properties> <slf4j.version>1.7.12</slf4j.version> </properties> <!-- 日志文件管理包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!--<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.25</version> </dependency>--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency>