myBatis 基礎測試 增 刪 改 查 用過hibrenate 之後,感覺很好理解

java的爪哇發表於2013-08-21

myBatis 基礎測試 增 刪 改 查 用過hibrenate 之後,感覺很好理解

免費下載: API:http://download.csdn.net/detail/liangrui1988/5988015

測試myelipse專案原始碼 sql 下載 http://download.csdn.net/detail/liangrui1988/5993881

sql 

| student | CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8 |

config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.2//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ruiabc"/>
<property name="username" value="root"/>
<property name="password" value="rui"/>
</dataSource>
</environment>
</environments>

<mappers>
<mapper resource="accp/bean/Student.xml"/>
</mappers>
</configuration>


mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.2//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="accp.dao">
<!--指定關係 -->
<resultMap type="accp.bean.Student" id="stuMAP">
 <result property="id" column="id" javaType="Integer" jdbcType="INTEGER"/>
 <result property="name" column="name" javaType ="string" jdbcType="VARCHAR"/>
 <result property="password" column="password" javaType ="string" jdbcType="VARCHAR"/>
 <result column="age" property="age" javaType="Integer" jdbcType="INTEGER"/>
</resultMap>


<select id="findStudentById" parameterType="int" resultType="accp.bean.Student">
select * from Student where id=#{id}
</select>

<select id="selectAllStu" resultType="accp.bean.Student">
select * from student
</select>

<insert id="addStudent" parameterType="accp.bean.Student">
INSERT INTO STUDENT(NAME,PASSWORD,AGE) 
	VALUES(#{name},#{password},#{age})
</insert>

<delete id="deleteStudent" parameterType="int">
delete from student where id=#{id}
</delete>

<update id="updateStudent" parameterType="accp.bean.Student">
update student set name=#{name},password=#{password},age=#{age} where id=#{id}
</update>

</mapper>

student.java

package accp.bean;

import java.io.Serializable;

public class Student implements Serializable {
	private Integer id;
	private String name;
	private String password;
	private Integer age;
	
	public Student(){}
	
	public Student(String name, String password, Integer age) {
		this.name = name;
		this.password = password;
		this.age = age;
	}
	
	public Integer getId() {
		return id;
	}
	
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}

	
}

dao 介面

package accp.dao;

import java.util.List;

import accp.bean.Student;

public interface Dao {
	
	boolean addStudent(Student stu);
	
	boolean updateStudent(Student stu);
	
	boolean deleteStudent(Student stu);
	
	boolean deleteStudent(int id);
	
	boolean findStudent(Student stu);
	
	Student findStudentById(int id);
	
	List<Student> findAll(); 

}

daoImp

package accp.dao.imp;


import java.util.List;

import org.apache.ibatis.session.SqlSession;
import accp.bean.Student;
import accp.dao.Dao;
import accp.util.GetSession;

public class DaoImp implements Dao {
	
	
    //取得sqlsession 在實際中是要把sqlsession放到一個操作下,不能共享
	SqlSession sqlSession=GetSession.getInstans().getSqlSession();
   
	@Override
	public boolean addStudent(Student stu) {
		 /**
	     * 最好都這樣做 安全的
	     */
		int count=0;
		try {
		count= sqlSession.insert("accp.dao.addStudent", stu);
		 sqlSession.commit(true);
		} catch (Exception e) {
		sqlSession.rollback();
		e.printStackTrace();
		}finally{
		//sqlSession.close();
		}
		return count<=0?false:true;
	}

	@Override
	public boolean updateStudent(Student stu) {
		int count=sqlSession.update("accp.dao.updateStudent", stu);
		sqlSession.commit(true);
		return count<=0?false:true;
	}

	@Override
	public boolean deleteStudent(Student stu) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean deleteStudent(int id) {
	int count= sqlSession.delete("accp.dao.deleteStudent",id);
	sqlSession.commit(true);
	return count<=0?false:true;
	}

	@Override
	public boolean findStudent(Student stu) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Student findStudentById(int id) {
		Student stu= sqlSession.selectOne("accp.dao.findStudentById",id);
		return stu;
	}

	@Override
	public List<Student> findAll() {
		List<Student> stu=sqlSession.selectList("accp.dao.selectAllStu");
		return stu;
		
	}

}

單例類: SqlSessionFactory

package accp.util;

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;

import accp.bean.Student;
import accp.dao.Dao;
import accp.dao.imp.DaoImp;
/**
 * 單例
 * @author liangrui
 *
 */
public class GetSession {
	
	private static GetSession getSession=null;
	
	 //載入xml配製資訊
	private static SqlSessionFactory sqlSessionFactory=null;
	
	private GetSession(){
	
		String sr="Configurationss.xml";
		//讀取xml
		Reader reader=null;
		try {
			reader=Resources.getResourceAsReader(sr);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//構建工廠例項
		sqlSessionFactory =new SqlSessionFactoryBuilder().build(reader);
		 System.out.println("hello....");
		/**
		 * 如果存在XML配置檔案的話,MyBatis將會自動查詢和載入一個對等的XML檔案(這種情況下,
		 * 基於類路徑下的BlogMapper.class類的類名,那麼BlogMapper.xml將會被載入)。
		 */
		 sqlSessionFactory.getConfiguration().addMapper(Dao.class);
		
	}
	
	//公有的獲取方法
	public  synchronized static GetSession getInstans(){
		if(getSession==null){
		getSession=new GetSession();
		}
		return getSession;
	}
	
	//獲取 sqlSessionFactory 例項
	public  static SqlSessionFactory getSqlSessionFactory(){
		return sqlSessionFactory;
	}
	
	//get sqlsession
	public static SqlSession getSqlSession(){
		return sqlSessionFactory.openSession();
	}
	
	//close
	public static void closeSqlSession(SqlSession se){
		if(se!=null){
		se.close();
		}
	}
}


Test:

package accp.test;

import java.util.List;
import accp.bean.Student;
import accp.dao.Dao;
import accp.dao.imp.DaoImp;

public class TestMyBatis {
	
	public static void main(String[] args) {

	Dao dao=new DaoImp();//業務介面
	
	//查詢 根據id------------------------------------------------------------------
	System.out.println("find: "+dao.findStudentById(1).getName());
		
	//add------------------------------------------------------------------
		//System.out.println("新增: "+dao.addStudent(new Student("hello","world",100)));
	
	//delete------------------------------------------------------------------	
		//System.out.println(dao.deleteStudent(18));
		
	//update------------------------------------------------------------------	
		/*Student stuUp= new Student("your","udser",33) ;
		stuUp.setId(1);
		System.out.println("update: "+dao.updateStudent(stuUp));*/
	
	//select all------------------------------------------------------------
		for(Student stu:dao.findAll()){
		System.out.println(stu.getId()+":  "+stu.getName()+"  "+stu.getPassword()+"  "+stu.getAge());
		}
		
		
	}
}




相關文章