mybatis入門程序(1)

1,建表語句:

create table students(
   id  int(5) primary key,
   name varchar(10),
   sal double(8,2)
);
2,javabean:
Student.java

/**
 * 學生
 * @author AdminTC
 */
public class Student {
	private Integer id;//編號
	private String name;//姓名
	private Double sal;//薪水
	public Student(){}
	public Student(Integer id, String name, Double sal) {
		this.id = id;
		this.name = name;
		this.sal = sal;
	}
	public Integer getId() {
		System.out.println("getId()");
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		System.out.println("getName()");
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Double getSal() {
		System.out.println("getSal()");
		return sal;
	}
	public void setSal(Double sal) {
		this.sal = sal;
	}
}
3.MybatisUtil.java

/**
 * 工具類
 * @author AdminTC
 */
public class MybatisUtil {
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
	private static SqlSessionFactory sqlSessionFactory;
	/**
	 * 加載位於src/mybatis.xml配置文件
	 */
	static{
		try {
			Reader reader = Resources.getResourceAsReader("mybatis.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	/**
	 * 禁止外界通過new方法創建 
	 */
	private MybatisUtil(){}
	/**
	 * 獲取SqlSession
	 */
	public static SqlSession getSqlSession(){
		//從當前線程中獲取SqlSession對象
		SqlSession sqlSession = threadLocal.get();
		//如果SqlSession對象爲空
		if(sqlSession == null){
			//在SqlSessionFactory非空的情況下,獲取SqlSession對象
			sqlSession = sqlSessionFactory.openSession();
			//將SqlSession對象與當前線程綁定在一起
			threadLocal.set(sqlSession);
		}
		//返回SqlSession對象
		return sqlSession;
	}
	/**
	 * 關閉SqlSession與當前線程分開
	 */
	public static void closeSqlSession(){
		//從當前線程中獲取SqlSession對象
		SqlSession sqlSession = threadLocal.get();
		//如果SqlSession對象非空
		if(sqlSession != null){
			//關閉SqlSession對象
			sqlSession.close();
			//分開當前線程與SqlSession對象的關係,目的是讓GC儘早回收
			threadLocal.remove();
		}
	}
	
	
	
	
	
	/**
	 * 測試
	 */
	public static void main(String[] args) {
		Connection conn = MybatisUtil.getSqlSession().getConnection();
		System.out.println(conn!=null?"連接成功":"連接失敗");
	}
}
4.Mybatis.xml文件

<?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="db.properties"/>

	
	<!-- 設置類型別名 -->
	<typeAliases>
		<typeAlias type="com.bmw.javaee.mybatis.app04.Student" alias="student"/>
	</typeAliases>
	

	<!-- 設置一個默認的連接環境信息 -->
	<environments default="mysql_developer">
	
	
		<!-- 連接環境信息,取一個任意唯一的名字 -->
		<environment id="mysql_developer">
			<!-- mybatis使用jdbc事務管理方式 -->
			<transactionManager type="jdbc"/>
			<!-- mybatis使用連接池方式來獲取連接 -->
			<dataSource type="pooled">
				<!-- 配置與數據庫交互的4個必要屬性 -->
				<property name="driver" value="${mysql.driver}"/>
				<property name="url" value="${mysql.url}"/>
				<property name="username" value="${mysql.username}"/>
				<property name="password" value="${mysql.password}"/>
			</dataSource>
		</environment>
		
		
		
		
		<!-- 連接環境信息,取一個任意唯一的名字 -->
		<environment id="oracle_developer">
			<!-- mybatis使用jdbc事務管理方式 -->
			<transactionManager type="jdbc"/>
			<!-- mybatis使用連接池方式來獲取連接 -->
			<dataSource type="pooled">
				<!-- 配置與數據庫交互的4個必要屬性 -->
				<property name="driver" value="${oracle.driver}"/>
				<property name="url" value="${oracle.url}"/>
				<property name="username" value="${oracle.username}"/>
				<property name="password" value="${oracle.password}"/>
			</dataSource>
		</environment>
	</environments>
	
	
	
	
	
	<!-- 加載映射文件-->
	<mappers>
		<mapper resource="com/bmw/javaee/mybatis/app04/StudentMapper.xml"/>
	</mappers>
	
	
	
</configuration>
5.db.properties

mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/mybatis
mysql.username=root
mysql.password=root

oracle.driver=oracle.jdbc.driver.OracleDriver
oracle.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
oracle.username=scott
oracle.password=tiger
6.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">

<!-- namespace屬性是名稱空間,必須唯一 -->
<mapper namespace="cn.itcast.javaee.mybatis.app04.Student">	
	
	<!-- resultMap標籤:映射實體與表 
		 type屬性:表示實體全路徑名
		 id屬性:爲實體與表的映射取一個任意的唯一的名字
	-->
	<resultMap type="student" id="studentMap">
		<!-- id標籤:映射主鍵屬性
			 result標籤:映射非主鍵屬性
		     property屬性:實體的屬性名
		     column屬性:表的字段名	 
		-->							
		<id property="id" column="id"/>
		<result property="name" column="name"/>
		<result property="sal" column="sal"/>
	</resultMap>

	
	<!-- 
		insert標籤:要書寫insert這麼一個sql語句
		id屬性:爲insert這麼一個sql語句取一個任意唯一的名字
		parameterType:要執行的dao中的方法的參數,如果是類的話,必須使用全路徑類
	-->
	<insert id="add1">
		insert into students(id,name,sal) values(1,'哈哈',7000)
	</insert>
	
	
	<insert id="add2" parameterType="student">
		insert into students(id,name,sal) values(#{id},#{name},#{sal})
	</insert>
	
	
	<insert id="add3" parameterType="student">
		insert into students(id,name,sal) values(#{id},#{name},#{sal})
	</insert>

</mapper>
7.StudentDao.java

/**
 * 持久層 
 * @author AdminTC
 */
public class StudentDao {
	/**
	 * 增加學生
	 */
	public void add1() throws Exception{
		SqlSession sqlSession = null;
		try{
			sqlSession = MybatisUtil.getSqlSession();
			//事務開始(默認)
			//讀取StudentMapper.xml映射文件中的SQL語句
			int i = sqlSession.insert("cn.itcast.javaee.mybatis.app04.Student.add1");
			System.out.println("本次操作影響了"+i+"行");
			//事務提交
			sqlSession.commit();
		}catch(Exception e){
			e.printStackTrace();
			//事務回滾
			sqlSession.rollback();
			throw e;
		}finally{
			MybatisUtil.closeSqlSession();
		}
	}
	/**
	 * 增加學生
	 */
	public void add2(Student student) throws Exception{
		SqlSession sqlSession = null;
		try{
			sqlSession = MybatisUtil.getSqlSession();
			//事務開始(默認)
			//讀取StudentMapper.xml映射文件中的SQL語句
			sqlSession.insert(Student.class.getName()+".add2",student);
			//事務提交
			sqlSession.commit();
		}catch(Exception e){
			e.printStackTrace();
			//事務回滾
			sqlSession.rollback();
			throw e;
		}finally{
			MybatisUtil.closeSqlSession();
		}
	}
	/**
	 * 增加學生
	 */
	public void add3(Student student) throws Exception{
		SqlSession sqlSession = null;
		try{
			sqlSession = MybatisUtil.getSqlSession();
			sqlSession.insert(Student.class.getName()+".add3",student);
			sqlSession.commit();
		}catch(Exception e){
			e.printStackTrace();
			sqlSession.rollback();
			throw e;
		}finally{
			MybatisUtil.closeSqlSession();
		}
	}
	
	public static void main(String[] args) throws Exception{
		StudentDao dao = new StudentDao();
		dao.add1();
		dao.add2(new Student(2,"呵呵",8000D));
		dao.add3(new Student(3,"嘻嘻",9000D));
		dao.add3(new Student(4,"笨笨",9000D));
	}
}










發佈了45 篇原創文章 · 獲贊 8 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章