1. 程式人生 > >Mybatis學習(一)環境搭建

Mybatis學習(一)環境搭建

整體程式碼結構:


mybatis-config.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>
	<!-- 定義別名 -->	
	<typeAliases>
		<typeAlias alias="role" type="com.learn.chapter2.po.Role" />
	</typeAliases>
	
	<!-- 定義資料庫資訊,預設使用development資料庫構建環境 -->
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC">
				<property name="autoCommit" value="false"/>
			</transactionManager>
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
				<property name="username" value="root"/>
				<property name="password" value="123456"/>
			</dataSource>
		</environment>
	</environments>
	
	
	<!-- 定義對映器 -->
	<mappers>
		<mapper resource="com/learn/chapter2/mapper/RoleMapper.xml" />
	</mappers>

</configuration>

RoleMapper.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.learn.chapter2.mapper.RoleMapper">
 	<!-- 查詢 -->
 	<select id="getRole" parameterType="long" resultType="role">
 		select id, 
 		       role_name as roleName,
 		       note 
 		   from t_role 
 		   where id = #{id} 
 	</select>
 	
 	<!-- 插入資料 -->
 	<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 t.id = #{id}
 	</delete>
 	
 
 </mapper>

RoleMapper.java

package com.learn.chapter2.mapper;

import com.learn.chapter2.po.Role;

public interface RoleMapper {
	public Role getRole(long id);
	public void insertRole(Role role);
	public void deleteRole(long id);
}


Role.java
package com.learn.chapter2.po;

public class Role {
	private Long id;
	private String roleName;
	private String note;
	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;
	}
	
	
	
}


SqlSessionFactoryUtil.java

package com.learn.chapter2.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;

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 org.apache.log4j.Logger;

public class SqlSessionFactoryUtil {
	//建立SqlSessionFactory例項
	//單例模式
	private static SqlSessionFactory sqlSessionFactory = null;
	
	//私有化構造方法
	private SqlSessionFactoryUtil(){};
	
	//類執行緒鎖
	@SuppressWarnings("rawtypes")
	private static final Class CLASS_LOCK = SqlSessionFactoryUtil.class;
	
	//建立例項
	public static SqlSessionFactory initSqlSessionFactory(){
		String resource = "mybatis-config.xml";
		InputStream inputStream = null;
		try{
			inputStream = Resources.getResourceAsStream(resource); 
		}catch (IOException e) {
			Logger.getLogger(SqlSessionFactoryUtil.class.getName()).log("", null, Level.SEVERE, e);
		}
		synchronized(CLASS_LOCK){
			if(sqlSessionFactory==null){
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			}
			return sqlSessionFactory;
		}
	}
	
	//建立sqlsession
	public static SqlSession openSqlSession(){
		if(sqlSessionFactory==null){
			initSqlSessionFactory();
		}
		return sqlSessionFactory.openSession();
	}
	
	
	
}


Chapter2Main.java

package com.learn.chapter2.main;

import org.apache.ibatis.session.SqlSession;

import com.learn.chapter2.mapper.RoleMapper;
import com.learn.chapter2.po.Role;
import com.learn.chapter2.util.SqlSessionFactoryUtil;

public class Chapter2Main {
	
	public static void main(String[] args) {
		SqlSession sqlSession = null;
		try{
			sqlSession  = SqlSessionFactoryUtil.openSqlSession();
			RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
			Role role = new Role();
			role.setNote("a litte boy");
			role.setRoleName("Tom");
			roleMapper.insertRole(role);
			sqlSession.commit();
			
			
			Role res = roleMapper.getRole(3);
			System.out.println("=================");
			System.out.println("Res: " + res.getId() + "\n" +res.getRoleName() + "\n" + res.getNote());
			System.out.println("=================");
			
			
		}catch(Exception ex){
			System.out.println("ex: " + ex.getMessage() + "\n");
			sqlSession.rollback();
		}finally{
			sqlSession.close();
		}
	}
	
}

log4j.properties

#配置log4j的屬性檔案
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


MySQL DML & DDL:

create database mybatis;

show databases;

use mybatis;

create table t_role(
	   id int(20) primary key not null auto_increment, 
	   role_name varchar(20), 
       note varchar(20)
);


show tables;

select * from t_role;

insert into t_role(role_name,note) value('HR','humen resources');
insert into t_role(role_name,note) value('IT','internet tech');

select * from t_role;

SQL:


Console:

DEBUG 2017-04-02 21:58:24,473 org.apache.ibatis.logging.LogFactory: Logging init

ialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.

DEBUG 2017-04-02 21:58:24,551 org.apache.ibatis.datasource.pooled.PooledDataSour

ce: PooledDataSource forcefully closed/removed all connections.

DEBUG 2017-04-02 21:58:24,554 org.apache.ibatis.datasource.pooled.PooledDataSour

ce: PooledDataSource forcefully closed/removed all connections.

DEBUG 2017-04-02 21:58:24,554 org.apache.ibatis.datasource.pooled.PooledDataSour

ce: PooledDataSource forcefully closed/removed all connections.

DEBUG 2017-04-02 21:58:24,554 org.apache.ibatis.datasource.pooled.PooledDataSour

ce: PooledDataSource forcefully closed/removed all connections.

DEBUG 2017-04-02 21:58:24,726 org.apache.ibatis.transaction.jdbc.JdbcTransaction

: Opening JDBC Connection

Sun Apr 02 21:58:24 CST 2017 WARN: Establishing SSL connection without server's 

identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ an

d 5.7.6+ requirements SSL connection must be established by default if explicit 

option isn't set. For compliance with existing applications not using SSL the ve

rifyServerCertificate property is set to 'false'. You need either to explicitly 

disable SSL by setting useSSL=false, or set useSSL=true and provide truststore f

or server certificate verification.

DEBUG 2017-04-02 21:58:25,074 org.apache.ibatis.datasource.pooled.PooledDataSour

ce: Created connection 507084503.

DEBUG 2017-04-02 21:58:25,075 org.apache.ibatis.transaction.jdbc.JdbcTransaction

: Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection

@1e397ed7]

DEBUG 2017-04-02 21:58:25,076 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>

  Preparing: insert into t_role(role_name,note) values (?,?) 

DEBUG 2017-04-02 21:58:25,128 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>

 Parameters: Tom(String), a litte boy(String)

DEBUG 2017-04-02 21:58:25,131 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==

    Updates: 1

DEBUG 2017-04-02 21:58:25,133 org.apache.ibatis.transaction.jdbc.JdbcTransaction

: Committing JDBC Connection [[email protected]]

DEBUG 2017-04-02 21:58:25,139 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>

  Preparing: select id, role_name as roleName, note from t_role where id = ? 

DEBUG 2017-04-02 21:58:25,140 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>

 Parameters: 3(Long)

DEBUG 2017-04-02 21:58:25,168 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==

      Total: 1

=================

Res: 3

Lucy

just mark

=================

DEBUG 2017-04-02 21:58:25,169 org.apache.ibatis.transaction.jdbc.JdbcTransaction

: Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connectio

[email protected]]

DEBUG 2017-04-02 21:58:25,174 org.apache.ibatis.transaction.jdbc.JdbcTransaction

: Closing JDBC Connection [[email protected]]

DEBUG 2017-04-02 21:58:25,174 org.apache.ibatis.datasource.pooled.PooledDataSour

ce: Returned connection 507084503 to pool.


相關推薦

Mybatis學習環境搭建

整體程式碼結構: mybatis-config.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Conf

Mybatis學習環境搭建之踩坑

第一次報錯: DEBUG 2017-03-30 01:37:40,043 org.apache.ibatis.logging.LogFactory: Logging init ialized usin

java學習 環境搭建、hello world的demo

環境變量 網上 類庫 .com java開發 www cnblogs rgs .class   本程序媛搞前端的,上班偶有空閑,不妨來學習學習,不然怎麽包養小白臉,走上人生巔峰?   說實話,每個語言都相通,有了javascript的基礎,並且有了兩三年跟java打交道的經

cpp學習環境搭建

方便 arm linux開發 箭頭 water RoCE 理解 eas 但是 想起我剛寫c++的時候,一把辛酸淚,還好有廣大碼友的幫助,最近時間充裕,整理一下學習c++的點滴,希望可以幫到剛入坑的朋友們。 一、 環境安裝一個優良的開發環境可以使學習更加順利,在熟練以

Python學習-環境搭建之PyCharm專業版漢化

Python學習(一)-環境搭建之PyCharm專業版漢化 1、找到lib所在安裝目錄 2、下載檔案 連結:https://pan.baidu.com/s/1B-Gw2F5zLTrWx7OCQNt87A 密碼:x10v 3、將下載好的resources_cn.jar放到li

Python學習-環境搭建之PyCharm專業版破解

PyCharm專業版破解 1、下載地址:https://www.jetbrains.com/pycharm/download/#section=windows 2、直接執行下載好的 3、選擇安裝路徑:E:\Pycharm\PyCharm 2018.2.4 4、根據電腦

Koa2學習環境搭建

Koa2學習(一)環境搭建 koa2腳手架 koa2服務安裝 koa2-generator目錄結構 什麼是 Koa2 koa 是由 Express 原班人馬打造的,致力於成為一個更小、更富有表現力、更健壯的 Web 框架。 使用 koa 編寫 web 應用,通過組合不

SpringMVC學習環境搭建以及HelloWorld

建立一個簡單的HelloWorld的SpringMVC例項 步驟一:新增 jar 包 所需jar包如下圖: 步驟二:配置 web.xml 檔案 DispatcherServlet是前置控制器,配置在web.xml檔案中的。攔截匹配的請求,Servlet攔截匹配規則要自已定義,把攔截下來的請求,依據相應的規

深度學習TensorFlow環境搭建硬體選購和主機組裝

一、硬體採購   近年來,人工智慧AI越來越多被人們所瞭解,尤其是AlphaGo的人機圍棋大戰之後,機器學習的熱潮也隨之高漲。最近,公司採購了幾批裝置,通過深度學習(TensorFlow)來研究金融行業相關問題,學習機器學習我們需要滿足一定的硬體要求,本文主要是介紹

自學mybatis-----環境搭建

一、簡介 mybatis是Apache的一個開源專案,應用在持久層,對比hibernate而言,個人感覺更輕量級,配置起來也更加簡單一些 二、建立工程以及環境配置 建立一個Dynamic Web Project,名字為mybatis1。如下圖就是我的專案架構 因為myb

Linux 4.10.8 根文件系統制作---環境搭建

zxvf fstab project 根據 構建 yaffs http tar.bz2 onf 一、工具   制作工具為busybox   下載地址:https://busybox.net/   解壓:    二、制作文件系統   進入目錄,執行make menuconfi

mybatis學習----入門

配置 ati 開源 bold 文件中 手動 arch mage git 一.Mybatis介紹 MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,並且改名為

MyBatis學習簡介及入門案例

結果集 提交 ace 支持 nag 實例 exce 空間 cti 1.什麽是MyBatis?   MyBatis是一個支持普通SQL查詢,存儲過程,和高級映射的優秀持久層框架。MyBatis去掉了幾乎所有的JDBC代碼和參數的手工設置以及對結果集的檢索封裝。MyBatis可

深度學習TensorFlow環境搭建Ubuntu16.04+CUDA8.0+cuDNN7+Anaconda4.4+Python3.6+TensorFlow1.3

缺失 應該 否則 wid -c 方式 *** 也不能 collected   緊接著上一篇的文章《深度學習(TensorFlow)環境搭建:(二)Ubuntu16.04+1080Ti顯卡驅動》,這篇文章,主要講解如何安裝CUDA+CUDNN,不過前提是我們是已經把NVID

MongoDB環境搭建與初始配置

dba 註意 管理員 開機自啟動 拓展 width 間接 face 環境搭建 前言   最近的項目中需要用到MongoDB,所這段時間需要學習知道怎麽去使用這個數據庫。   這裏我先簡單的介紹一下什麽是MongoDB,後面還會詳細的介紹:     MongoDB 是一

MyBatis 學習

style spring exception pan internet 現象 nec mes 事務提交 一、MyBatis 1、MyBatis 介紹(百度)   MyBatis 是一款優秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所

使用JAVA開發微信公眾平臺——環境搭建與開發接入

iges 微信平臺 校驗 後臺服務 結果 png 交互 package app 一、 初始微信公眾平臺 微信公眾平臺,即我們平時所說的“公眾號”,曾用名“官方平臺”、“媒體平臺”,但最終命名為&ldq

Python3與OpenCV3.3 圖像處理--環境搭建與簡單DEMO

http opencv3 opencv col lan pytho href tar .net https://blog.csdn.net/qq_32811489/article/details/78636049 https://blog.csdn.net/gangzhu

ctrl_c + ctrl_v 出來的四不像 -- 環境搭建

mysq 導入 技術分享 lob 解決 ear lang .sql ati 一、基礎環境   .net Core:https://www.microsoft.com/net/learn/dotnet/hello-world-tutorial   docker:https

Jmeter學習--環境配置

text ftp服務器 自己 等等 csdn 測試 java www. 出現 前言: 最近從上家公司離職,進入某外包公司做接口測試,由於之前只會用soapui和postman進行接口測試(初級的請求),這次趁著放假,搗鼓一下jmeter 老規矩,先了解jmete