1. 程式人生 > >mybatis總結(一)

mybatis總結(一)

tran default led sqlserver insert cto src 結果集 obj

MyBatis

是支持普通 SQL查詢,存儲過程和高級映射的優秀持久層框架。MyBatis 消除了幾乎所有的JDBC代碼和參數的手工設置以及結果集的檢索。MyBatis 使用簡單的 XML或註解用於配置和原始映射,將接口和 Java 的POJOs(Plain Ordinary Java Objects,普通的 Java對象)映射成數據庫中的記錄。

1.首先搭建一個maven項目,引入oracle和mysql配置jar包,本文主要演示mysql

技術分享

2.在數據庫中創建表與數據

CREATE TABLE `student` (
`studentno` int(11) NOT NULL ,
`name` char(10) default NULL,
PRIMARY KEY (`studentno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=‘姓名‘;

INSERT INTO `student` VALUES (‘1‘, ‘張三‘);
INSERT INTO `student` VALUES (‘2‘, ‘李四‘);

3.創建表的實體類

public class Student {
    private int studentno;//學生編號
    private String name;//學生姓名
    public int getStudentno() {
        return studentno;
    }
    public void setStudentno(int studentno) {
        this
.studentno = studentno; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

4.創建接口StudentMapper和StudentMapper.xml

接口StudentMapper:

public interface StudentMapper {
    public Student selectStudent(int studentno);
}

StudentMapper.xml

<?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.qyxy.mapper.StudentMapper">

   <select id="selectStudent" resultType="Student">
    select * from student where studentno = #{studentno}
  </select>
  
</mapper>

註意:接口中的方法和select中id的名字是一致的

5.接數據庫的文件db.properties

jdbc.driverClassName=com.mysql.jdbc.Driver//根據自己數據庫,自己改
jdbc.url=jdbc:mysql://localhost:3306/hello//根據自己數據庫,自己改
jdbc.username=root//根據自己數據庫,自己改
jdbc.password=123456//根據自己數據庫,自己改

6.配置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>

	<!-- properties屬性配置文件的引入 -->
	<properties resource="db.properties"></properties>
	<!-- setting設置,調整mybaits運行行為 -->
	<settings>
	  <!-- 匹配下劃線到駝峰式命名法 -->
	  <setting name="mapUnderscoreToCamelCase" value="true"/>
	  <setting name="safeRowBoundsEnabled" value="false"/>
	  <setting name="cacheEnabled" value="true"/>
	  <setting name="lazyLoadingEnabled" value="true"/>
	  <setting name="multipleResultSetsEnabled" value="true"/>
	  <setting name="useColumnLabel" value="true"/>
	  <setting name="useGeneratedKeys" value="false"/>
	  <setting name="autoMappingBehavior" value="PARTIAL"/>
	  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
	  <setting name="defaultExecutorType" value="SIMPLE"/>
	  <setting name="defaultStatementTimeout" value="25"/>
	  <setting name="defaultFetchSize" value="100"/>
	  <setting name="localCacheScope" value="SESSION"/>
	  <setting name="jdbcTypeForNull" value="OTHER"/>
	  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
	</settings>
	<!-- 類起別名 -->
	<typeAliases>
		<!-- <typeAlias type="com.qyxy.entity.Dept" alias="Dept"/> -->
		<package name="com.qyxy.entity"/>
	</typeAliases>
	<!-- 設置要使用的數據庫環境 -->
	<environments default="mysql">
		<environment id="mysql">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driverClassName}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
		
	</environments>

	<!-- 定義不同的數據庫廠商標識 -->
	<databaseIdProvider type="DB_VENDOR">
	  <property name="SQL Server" value="sqlserver"/>
	  <property name="DB2" value="db2"/>        
	  <property name="Oracle" value="oracle" />
	  <property name="MySql" value="mysql" />
	</databaseIdProvider>

	<!-- 映射的sql文件 -->
	<mappers>
		<mapper resource="StudentMapper.xml" />
		
	</mappers>
</configuration>

所有的配置,都已經弄好,下面開始編寫測試類測試

7.測試類

public class StudentTest {
	public static void main(String[] args) throws IOException {
		// 指定mybatis配置文件路徑和文件名
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
				.build(inputStream);
		SqlSession session = sqlSessionFactory.openSession();
		try {
			// session.selectOne(配置文件中namespace.id,傳入參數的值)
			//通過接口,調用方法(接口名和namespace名稱保持一致,id和方法名保持一致)
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			Student student = mapper.selectStudent(2);		
			System.out.println(student.getStudentno()+"-----"+student.getName());
		} finally {
			session.close();
		}

	}
}

8.測試結果:

技術分享

mybatis總結(一)