Mybatis簡單應用
阿新 • • 發佈:2018-11-03
ack clas XML inf ctype date conf inter space
Mybatis的核心組件:
- SqlSeeeionFactoryBuilder (構建器):它會根據配置或者代碼來生成SqlSessionFactory,采用的是分布構建的Builder模式;
- SqlSessionFactory:依靠它來生成SqlSession,使用的是工廠模式。
- SqlSession(會話)發送SQL執行並返回結果,也可以獲取Mapper接口。
- SQL Mapper(映射器): 由一個java接口和XML文件(或註解)構成,需要給出SQL的映射規則。它負責發送SQL去執行返回結果。
1.使用XML:mybatis-config.xml創建SqlSessionFactory的配置;
<?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.learn.ssm.chapter3.pojo.Role"/> </typeAliases> <!-- 數據庫環境 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/ssm"/> <property name="username" value="root"/> <property name="password" value="admin123"/> </dataSource> </environment> </environments> <!-- 映射文件 --> <mappers> <mapper resource="com/learn/ssm/chapter3/mapper/RoleMapper.xml"/> <mapper class="com.learn.ssm.chapter3.mapper.RoleMapper2"/> </mappers> </configuration>
1.1 使用代碼或xml創建SqlSessionFactory
package com.learn.ssm.chapter3.utils; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.datasource.pooled.PooledDataSource; import org.apache.ibatis.io.Resources; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.transaction.TransactionFactory; import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import com.learn.ssm.chapter3.mapper.RoleMapper; import com.learn.ssm.chapter3.mapper.RoleMapper2; import com.learn.ssm.chapter3.pojo.Role; public class SqlSessionFactoryUtils { private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class; private static SqlSessionFactory sqlSessionFactory = null; private SqlSessionFactoryUtils() { } public static SqlSessionFactory getSqlSessionFactory() { 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; } } //代碼生成SqlSessionFactory public static SqlSessionFactory getSqlSessionFactory2() { synchronized (LOCK) { //數據庫連接池信息 PooledDataSource dataSource = new PooledDataSource(); dataSource.setDriver("com.mysql.jdbc.Driver"); dataSource.setUsername("root"); dataSource.setPassword("admin123"); dataSource.setUrl("jdbc:mysql://localhost:3306/ssm"); dataSource.setDefaultAutoCommit(false); //采用MyBatis的JDBC事務方式 TransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("development", transactionFactory, dataSource); //創建Configuration對象 Configuration configuration = new Configuration(environment); //註冊一個MyBatis上下文別名 configuration.getTypeAliasRegistry().registerAlias("role", Role.class); //加入一個映射器 configuration.addMapper(RoleMapper.class); configuration.addMapper(RoleMapper2.class); //使用SqlSessionFactoryBuilder構建SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); return sqlSessionFactory; } } public static SqlSession openSqlSession() { if (sqlSessionFactory == null) { getSqlSessionFactory(); } return sqlSessionFactory.openSession(); } }
2. 映射器,由一個java接口和XML文件(或註解)構成
首先定義一個POJO
package com.learn.ssm.chapter3.pojo; public class Role { private Long id; private String roleName; private String note; /** setter and getter **/ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
2.1, 接口和XML實現映射
映射器接口:
public interface RoleMapper { public int insertRole(Role role); public int deleteRole(Long id); public int updateRole(Role role); public Role getRole(Long id); public List<Role> findRoles(String roleName); }
在XML創建SqlSession中有這樣代碼
<mapper resource="com/learn/ssm/chapter3/mapper/RoleMapper.xml"/>
引入XML(RoleMapper.xml)創建映射器(insert/select/update/delete)代表增/查/改/刪
id 代表RoleMapper中方法名字
parameterType代表傳入參數類型
resultType代表返回值 "role"是別名,代表<typeAlias alias="role" type="com.learn.ssm.chapter3.pojo.Role"/>
<?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.learn.ssm.chapter3.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>
2.2註解實現映射器
XML中引入Mapper:
<mapper class="com.learn.ssm.chapter3.mapper.RoleMapper2"/>
public interface RoleMapper2 { @Select("select id, role_name as roleName, note from t_role where id=#{id}") public Role getRole(Long id); @Insert("insert into t_role(role_name,note) values(#{roleName},#{note})") public void insertRole(Role role); }
註解不易於維護
3. 測試:
public class Chapter3Main { public static void main(String[] args) { testRoleMapper(); testRoleMapper2(); } //xml 測試 private static void testRoleMapper() { Logger log = Logger.getLogger(Chapter3Main.class); SqlSession sqlSession = null; try { sqlSession = SqlSessionFactoryUtils.openSqlSession(); RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class); Role role = roleMapper.getRole(1L); Role r1 = new Role(); r1.setRoleName("testRole name"); r1.setNote("note..."); roleMapper.insertRole(r1); sqlSession.commit(); log.info(role.getRoleName()); } catch(Exception ex) { sqlSession.rollback(); } finally { if (sqlSession != null) { sqlSession.close(); } } } //註解SQL測試 private static void testRoleMapper2() { Logger log = Logger.getLogger(Chapter3Main.class); SqlSession sqlSession = null; try { sqlSession = SqlSessionFactoryUtils.openSqlSession(); RoleMapper2 roleMapper2 = sqlSession.getMapper(RoleMapper2.class); Role role = roleMapper2.getRole(1L); Role r1 = new Role(); r1.setRoleName("testRole name map2"); r1.setNote("note..."); roleMapper2.insertRole(r1); sqlSession.commit(); log.info(role.getRoleName()); } catch(Exception ex) { sqlSession.rollback(); } finally { if (sqlSession != null) { sqlSession.close(); } } } }
Mybatis簡單應用