MyBatis3 之 CRUD

MyBatis3  之  CRUD: java

jar包就不上了,主要看代碼。先總覽一下文件結構: mysql

下面是代碼: sql

1)configuration.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 resource="jdbc.properties"/>
	
	<!-- 設置緩存和延遲加載等等重要的運行時的行爲方式 -->
	<settings>
		<!-- 設置超時時間,它決定驅動等待一個數據庫響應的時間  -->
		<setting name="defaultStatementTimeout" value="25000"/>
	</settings>
	
	<!-- 別名 -->
	<typeAliases>
		<typeAlias alias="User" type="com.mybatis.model.User"/>
	</typeAliases>
	
	<environments default="development">
		<!-- environment 元素體中包含對事務管理和鏈接池的環境配置 -->
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="${driver}" />
				<property name="url" value="${url}" />
				<property name="username" value="${username}" />
				<property name="password" value="${password}" />
			</dataSource>
		</environment>
	</environments>
	
	<!-- ORM映射文件 -->
	<mappers>
		<mapper resource="com/mybatis/model/UserSqlMap.xml" />
	</mappers>
	
</configuration>



 2)jdbc.properties apache


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


3)log4j.properties



log4j.rootLogger=DEBUG,A1
# \u8f93\u51fa\u5230\u63a7\u5236\u53f0 
log4j.appender.A1=org.apache.log4j.ConsoleAppender 
log4j.appender.A1.layout=org.apache.log4j.PatternLayout 
log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} [\u65E5\u5FD7\u4FE1\u606F] %m%n


4)User .java



package com.mybatis.model;

import java.io.Serializable;

@SuppressWarnings("serial")
public class User implements Serializable {
	
	private int id;
	private String userName;
	private String password;
	
	public User(){
	}
	
	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 getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

}


5)UserSqlMap.xml



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper     
PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"     
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">     
   
<!-- namespace用於java代碼調用時識別指定xml的mapper文件 -->
<mapper namespace="com.mybatis.model.User">
	<!-- 配置ORM映射 -->
	<resultMap type="User" id="user_orm">
		<id property="id" column="id"/>
		<result property="userName" column="userName"/>
		<result property="password" column="password"/>
	</resultMap>
	
	<!-- 用來定義可重用的SQL代碼段 -->
	<sql id="demo_sql">
       userName,password
	</sql>
	
	<insert id="inser_user" parameterType="User">
		<!-- include 引用可重用的SQL代碼段 -->
		INSERT INTO USER(<include refid="demo_sql"/>) VALUES(#{userName},#{password})
	</insert>
	
	<update id="update_user" parameterType="User">
		UPDATE USER SET userName=#{userName} ,password=#{password}  WHERE id=#{id}
	</update>
	
	<update id="delete_user" parameterType="int">
		DELETE FROM USER WHERE id=#{id}
	</update>
  
    <select id="selectAll_user" useCache="false" flushCache="true" resultMap="user_orm">
    	SELECT * FROM USER
  	</select>
  	
  	<!-- 使用map傳人多個參數 -->
    <select id="selectList_user" useCache="false" flushCache="true" parameterType="map" resultMap="user_orm">
    	SELECT * FROM USER LIMIT #{pageNow},#{pageSize} 
  	</select>
  	
  	<select id="selectById_user" parameterType="int" resultType="User">
    	SELECT * FROM USER WHERE id= #{id}
  	</select>
  	
  	<select id="selectCount_user"  resultType="int">
    	SELECT count(*) FROM USER 
  	</select>
  	
  	<select id="selectByName_user" parameterType="String" resultType="User">
    	SELECT * FROM USER WHERE userName= #{userName}
  	</select>
  	
</mapper>


6)SessionFactoryUtil.java  MyBatis工具類,用於建立SqlSessionFactory



package com.mybatis.sessionfactory;

import java.io.IOException;
import java.io.Reader;

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 SessionFactoryUtil {
	
	private static final String RESOURCE = "Configuration.xml";
	private static SqlSessionFactory sqlSessionFactory = null;
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

	static {
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader(RESOURCE);
		} catch (IOException e) {
			throw new RuntimeException("Get resource error:"+RESOURCE, e);
		}

		sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
	}
	
	/**
	 * Function  : 得到SqlSessionFactory
	 */
	public static SqlSessionFactory getSqlSessionFactory(){   
        return sqlSessionFactory;   
    }
	
	/**
	 * Function  : 從新建立SqlSessionFactory
	 */
	public static void rebuildSqlSessionFactory(){
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader(RESOURCE);
		} catch (IOException e) {
			throw new RuntimeException("Get resource error:"+RESOURCE, e);
		}

		sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
	}
	
	/**
	 * Function  : 獲取sqlSession
	 */
	public static SqlSession getSession(){
		SqlSession session = threadLocal.get();
		
		if(session!=null){
			if(sqlSessionFactory == null){
				getSqlSessionFactory();
			}
			//若是sqlSessionFactory不爲空則獲取sqlSession,不然返回null
			session = (sqlSessionFactory!=null) ? sqlSessionFactory.openSession(): null;
		}
		
		return session;
	}
	
	/**
	 * Function  : 關閉sqlSession
	 */
	public static void closeSession(){
		SqlSession session = threadLocal.get();
		threadLocal.set(null);
		if(session!=null){
			session.close();
		}
	}
}


7)UserDao interface



package com.mybatis.dao;

import java.util.List;

import com.mybatis.model.User;

public interface UserDao {
	
	public User load(int id);
	public void add(User user);
	public void update(User user);
	public void delete(int id);
	public User findByName(String userName);
	public List<User>  queryAllUser();
	public List<User> list(int pageNow,int pageSize);
	public int getAllCount();
	
}


8)UserDaoImpl 緩存


package com.mybatis.dao.implment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.mybatis.dao.UserDao;
import com.mybatis.model.User;
import com.mybatis.sessionfactory.SessionFactoryUtil;


public class UserDaoImpl implements UserDao {
	
	public User load(int id){
		SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();
		User user = (User) session.selectOne("com.mybatis.model.User.selectById_user", id);
		session.close();
		return user;
	}

	public void add(User user) {
		SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();
		session.insert("com.mybatis.model.User.inser_user", user);
		session.commit();
		session.close();
	}
	
	public void update(User user){
		SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();
		session.update("com.mybatis.model.User.update_user", user);
		session.commit();
		session.close();
	}
	
	public void delete(int id){
		SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();
		session.delete("com.mybatis.model.User.delete_user",id);
		session.commit();
		session.close();
	}
	
	public User findByName(String userName){
		SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();
		User user = (User)session.selectOne("com.mybatis.model.User.selectByName_user", userName);
		session.close();
		return user;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> queryAllUser() {
		SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();
		List<User> list = session.selectList("com.mybatis.model.User.selectAll_user");
		session.close();
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> list(int pageNow , int pageSize){
		SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession();
		Map<String,Object> params = new HashMap<String ,Object>();
		params.put("pageNow", (pageNow-1)*pageSize);
		params.put("pageSize", pageSize);
		List<User> list = session.selectList("com.mybatis.model.User.selectList_user", params);
		session.close();
		return list;
	}
	
	public int getAllCount(){
		SqlSession session =SessionFactoryUtil.getSqlSessionFactory().openSession();
		int count = (Integer) session.selectOne("com.mybatis.model.User.selectCount_user");
		session.close();
		return count;
	}
	
}



9)測試類:



package com.mybatis.dao.implment;

import java.util.List;

import org.junit.Test;

import com.mybatis.dao.UserDao;
import com.mybatis.model.User;

public class UserDaoTest {
	
	private UserDao userDao = new UserDaoImpl();
	
	@Test
	public void testLoad(){
		User u = userDao.load(1);
		if(u!=null){
			System.out.println("UserId:"+u.getId()+"  UserName:"+u.getUserName()+"  Password:"+u.getPassword());
		}
		else{
			System.out.println("id不存在!!");
		}
	}
	
	@Test
	public void testAdd(){
		User user = new User();
		user.setUserName("admin5");
		user.setPassword("123456");
		userDao.add(user);
	}
	
	@Test
	public void testUpdate(){
		User user = new User();
		user.setId(2);
		user.setUserName("manager");
		user.setPassword("123456");
		userDao.update(user);
	}
	
	@Test
	public void testQueryAllUser(){
		List<User> list = userDao.queryAllUser();
		if(list!=null&list.size()>0){
			for(User u:list){
				System.out.println("UserId:"+u.getId()+"  UserName:"+u.getUserName()+"  Password:"+u.getPassword());
			}
		}
	}
	
	@Test
	public void testFindByName(){
		User u = userDao.findByName("admin");
		if(u!=null){
			System.out.println("UserId:"+u.getId()+"  UserName:"+u.getUserName()+"  Password:"+u.getPassword());
		}
		else{
			System.out.println("用戶名不存在!!");
		}
	}
	
	@Test
	public void testList(){
		List<User> list = userDao.list(1, 4);
		if(list!=null&list.size()>0){
			for(User u:list){
				System.out.println("UserId:"+u.getId()+"  UserName:"+u.getUserName()+"  Password:"+u.getPassword());
			}
		}
	}
	
	@Test
	public void testGetAllCount(){
			System.out.println("All Count : "+userDao.getAllCount());
	}
	
	@Test
	public void testDelete(){
		userDao.delete(3);
	}

}


10)執行testFindByName() session

輸出: mybatis

2012-10-26 23:45:46 [日誌信息] ooo Connection Opened
2012-10-26 23:45:46 [日誌信息] ==>  Executing: SELECT * FROM USER WHERE userName= ? 
2012-10-26 23:45:46 [日誌信息] ==> Parameters: admin(String)
2012-10-26 23:45:47 [日誌信息] <==    Columns: id, userName, password
2012-10-26 23:45:47 [日誌信息] <==        Row: 1, admin, 123456
2012-10-26 23:45:47 [日誌信息] xxx Connection Closed
2012-10-26 23:45:47 [日誌信息] Returned connection 18093747 to pool.
UserId:1  UserName:admin  Password:123456
相關文章
相關標籤/搜索