码迷,mamicode.com
首页 > 其他好文 > 详细

mybatis---demo1--(单表增删改查)----bai

时间:2017-01-12 18:24:44      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:value   tor   actor   odi   测试   sql   etc   sel   man   

实体类:

package com.etc.entity;

public class News 
{
	private int id;
	private String title;
	private String content;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	@Override
	public String toString() {
		return "News [content=" + content + ", id=" + id + ", title=" + title
				+ "]";
	}	
}
========================================================================
dao类:

package com.etc.dao;

import java.util.List;

import com.etc.entity.News;

public interface NewsDao 
{
	List<News> findAll();
	News findById(int id);//精确查询
	void add(News news);//添加
	void update(News news);//修改
	void delete(Integer id);//删除
}
==========================================================================
工具类:

package com.etc.utils;

import java.io.InputStream;
import java.sql.Connection;

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.lf5.util.Resource;

//实现获取、释放mybatis数据库连接的工具类
public class MyBatisSessionFactory {
	//定义常量
	private static String CONFIG_FILE_LOCATION="mybatis-config.xml";
	
	//考虑到该工具类允许被多线程执行。因为封装1个线程池,让每个线程从线程池中获取1个连接。让1个线程对应
	//1条数据库连接,这样更安全
	//ThreadLocal的作用:让"线程"绑定"资源",这样就不会出现多个线程同享资源的情况。更安全。牺牲内存,换取”安全“
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
	
	private static InputStream is; //用于读取配置文件的流对象
	
	private static SqlSessionFactory fac;//用于管理多个连接的工厂。一个工厂对应1个数据库。
	
	//在该类的静态段中加载配置文件,这样可以确保只执行1次。
	static
	{
		try {
			is = Resources.getResourceAsStream(CONFIG_FILE_LOCATION);//读取配置文件
			fac = new SqlSessionFactoryBuilder().build(is);//通过配置文件创建1个连接工厂
		} catch (Exception e) 
		{
			e.printStackTrace();
		}
		
	}
	//获取1条连接
	public static SqlSession getSession()
	{
		SqlSession s  = threadLocal.get(); //找线程池要1条连接
		if(s==null) //第1次时,拿不到,则由工厂获取1条连接并放入线程池
		{
			s = fac.openSession();//由工厂获取1条连接并放入线程池
			threadLocal.set(s);//放入线程池
		}
		return s;
	}
	
	//关闭连接
	public static void closeSession()
	{
		SqlSession s  = threadLocal.get();//找线程池要本线程对应的连接
		threadLocal.set(null);//将该连接从线程池中清除
		if(s!=null)
			s.close();//物理关闭连接
	}
}
=======================================================================
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 type="com.etc.entity.News" alias="News"/>
</typeAliases>
<environments default="development">
<environment id="development">
   <transactionManager type="JDBC"/>
   <dataSource type="POOLED">	  
  	<property name="url" value="jdbc:mysql://127.0.0.1/java?characterEncoding=utf-8"/>
  	<property name="username" value="root"/>
  	<property name="password" value="root"/>
  	<property name="driver" value="com.mysql.jdbc.Driver"/>
  </dataSource>
</environment>
</environments>
<mappers>
  <mapper resource="com/etc/mapper/News-mapper.xml"/>
</mappers>
</configuration>
========================================================================
News-mapper.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">
<!-- 既是实体的映射文件。类似orm。同时又是dao的实现代码 -->
<mapper namespace="com.etc.dao.NewsDao">
<!-- 配置实体和数据表的映射关系 -->
<resultMap type="News" id="NewsResult">
	<id column="id" property="id"/>  <!-- 主键 -->
	<result column="title" property="title"/>
	<result column="content" property="content"/>
</resultMap>
 <!-- 查询全部,实现findAdd方法 -->
<select id="findAll" resultMap="NewsResult">
	select * from news	
</select>
<!-- 精确查询 ,实现findbyid的方法-->
<select id="findById" parameterType="java.lang.Integer" resultType="News">
	select * from news where id=#{id}
</select>
<!-- 添加 -->
<insert id="add" parameterType="News" >
	insert into news (title,content) values(#{title},#{content})
</insert>
<!-- 修改-->
<update id="update" parameterType="News" >
	update news set title=#{title},content=#{content} where id=#{id}
</update>
<!-- 删除 -->
<delete id="delete" parameterType="java.lang.Integer">
	delete from news where id=#{id}
</delete>
</mapper>
==========================================================================
测试类:

package com.etc.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.etc.dao.NewsDao;
import com.etc.entity.News;
import com.etc.utils.MyBatisSessionFactory;
public class TestNewsDao {	
	@Test
	public void testFindAll()
	{
		// 1 获取连接
		SqlSession session = MyBatisSessionFactory.getSession();	
		//2 执行查询
		List<News> list = session.getMapper(NewsDao.class).findAll();
		for(News n:list)
			System.out.println(n);
		//3 关闭
		MyBatisSessionFactory.closeSession();
	}
	//@Test
	public  void testFindById()
	{
		// 1 获取连接
		SqlSession session = MyBatisSessionFactory.getSession();	
		//2 执行查询
		News n = session.getMapper(NewsDao.class).findById(2);
		System.out.println(n);
		//3 关闭
		MyBatisSessionFactory.closeSession();
	}
	//@Test
	public void testadd()
	{
		// 1 获取连接
		SqlSession session = MyBatisSessionFactory.getSession();
		
		//2 执行添加
		News n = new News();
		n.setTitle("新的主题");
		n.setContent("新的内容");
		try {
			session.getMapper(NewsDao.class).add(n);
			session.commit();
			System.out.println("添加成功");
		} catch (Exception e) 
		{
			System.out.println("添加失败:");
			e.printStackTrace();
			session.rollback();
		}
		//3 关闭
		MyBatisSessionFactory.closeSession();
	}
	//@Test
	public void testupdate()
	{
		// 1 获取连接
		SqlSession session = MyBatisSessionFactory.getSession();
		
		//2 执行添加
		News n = new News();
		n.setId(4);
		n.setTitle("全新的主题");
		n.setContent("全新的内容");
		try {
			session.getMapper(NewsDao.class).update(n);
			session.commit();
			System.out.println("修改成功");
		} catch (Exception e) 
		{
			System.out.println("修改失败:");
			e.printStackTrace();
			session.rollback();
		}
		//3 关闭
		MyBatisSessionFactory.closeSession();

	}
	//@Test
	public void testdelete()
	{
		// 1 获取连接
		SqlSession session = MyBatisSessionFactory.getSession();	
		//2 执行添加
		try {
			session.getMapper(NewsDao.class).delete(4);
			session.commit();
			System.out.println("删除成功");
		} catch (Exception e) 
		{
			System.out.println("删除失败:");
			e.printStackTrace();
			session.rollback();
		}
		//3 关闭
		MyBatisSessionFactory.closeSession();
	}
}
=========================================================================

  

mybatis---demo1--(单表增删改查)----bai

标签:value   tor   actor   odi   测试   sql   etc   sel   man   

原文地址:http://www.cnblogs.com/ipetergo/p/6279227.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!