MyBatis入門基本的配置介紹

工具:Eclipsejava

首先下載Mabatis所須要的jar包,導包mysql

 

而後配置mybatis核心文件取名mybatis.xmlweb

<?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="jdbc_mysql.properties"/>
	
	<!-- 和spring整合後 environments配置將廢除-->
	<environments default="development">
		<environment id="development">
		<!-- 使用jdbc事務管理-->
			<transactionManager type="JDBC" />
		<!-- 數據庫鏈接池-->
			<dataSource type="POOLED">
				<property name="driver" value="${jdbc.driver}" />
				<property name="url" value="${jdbc.url}" />
				<property name="username" value="${jdbc.username}" />
				<property name="password" value="${jdbc.password}" />
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		<mapper resource="User.xml"/>
	</mappers>

</configuration>

而後配置鏈接數據庫的資源文件,取名 jdbc_mysql.properties,取名要有意義spring

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123

而後配置日誌文件,也就是查詢時輸出SQL語句sql

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

而後建立一個實體User數據庫

package cn.web.entity;

import java.util.Date;

public class User {
	private int id;
	private String username;// 用戶姓名
	private String sex;// 性別
	private Date birthday;// 生日
	private String address;// 地址
	
	
	public User() {
		super();
	}
	public User(int id, String username, String sex, Date birthday, String address) {
		super();
		this.id = id;
		this.username = username;
		this.sex = sex;
		this.birthday = birthday;
		this.address = address;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address="
				+ address + "]";
	}
	
	
}

而後就是Mybatis關鍵的一步了配置實體映射的查詢語句apache

<?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="cn.web">


  <select id="findUserid" parameterType="int" resultType="cn.web.entity.User">
  	SELECT * FROM USER WHERE id = #{id}
  </select>
  
  <select id="findUname" parameterType="String" resultType="cn.web.entity.User">
  	SELECT * FROM USER WHERE username LIKE #{username}
  	<!-- SELECT * FROM USER WHERE username LIKE concat('%',#{username},'%') -->
  	<!-- SELECT * FROM USER WHERE username LIKE '%' #{username} '%' -->
  </select>
  
  <delete id="deleteByid" parameterType="int">
		delete from User where id=#{id}  	
  </delete>
  
  <insert id="insert" parameterType="cn.web.entity.User">
  	<selectKey databaseId="id" order="AFTER">
  		SELECT LAST_INSERT_ID()
  	</selectKey>
  	INSERT INTO USER (id,username,sex,birthday,address) VALUES (#{id},#{username},#{sex},#{birthday},#{address})
  </insert>
  
  <update id="update" parameterType="cn.web.entity.User">
  	UPDATE USER SET username=#{username} WHERE id=#{id} 
  </update>
  
  
</mapper>

最後編寫一個數據鏈接的MybatisUtil,用來鏈接數據庫session

package cn.web.entity;

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;

public  class MyBatisUtil {
	
	private static SqlSessionFactory sqlSessionFactory;
	
	public static SqlSession getSqlSession(){
		try {
			InputStream is = Resources.getResourceAsStream("mybatis.xml");
			if(sqlSessionFactory == null){
				sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
			}
			return sqlSessionFactory.openSession();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}

最後一步編寫Test測試文件mybatis

package cn.web.entity;

import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class Test {
	@org.junit.Test
	public void testName() throws Exception {
		//mybatis配置文件
		String resource ="mybatis.xml" ;
		//獲得流對象
		InputStream inputStream = Resources.getResourceAsStream(resource) ;
		//建立會話工廠
		SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(inputStream);
		//經過會話工廠獲得會話
		SqlSession sqs= ssf.openSession();
		//經過會話建立數據庫
		User user=sqs.selectOne("cn.web.findUserid",40);
		System.out.println(user);
		//List<User> list= sqs.selectList("cn.web.findUname", "張"+"%");
		//sqs.insert("cn.web.insert",new User(40,"Make","2",new Date(),"珠海"));
		//sqs.update("cn.web.update", new User(40,"小楊",null,null,null));
		//sqs.delete("cn.web.deleteByid",30);
		//SELECT LAST_INSERT_ID()
		sqs.commit();
		//關閉會話
		sqs.close();
	}
	
}

測試成功經過app

相關文章
相關標籤/搜索