Mybatis连接Oracle数据库项目实现增删改查功能代码优化版

entity层代码:

package com.baizhi.entity;

import java.io.Serializable;

public class Account implements Serializable{
	private Integer card_id;
	private String username;
	private String password;
	private Double balance;
	private String mobile;
	public Integer getCard_id() {
		return card_id;
	}
	public void setCard_id(Integer card_id) {
		this.card_id = card_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;
	}
	public Double getBalance() {
		return balance;
	}
	public void setBalance(Double balance) {
		this.balance = balance;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	@Override
	public String toString() {
		return "Account [card_id=" + card_id + ", username=" + username + ", password=" + password + ", balance="
				+ balance + ", mobile=" + mobile + "]";
	}
	public Account(Integer card_id, String username, String password, Double balance, String mobile) {
		super();
		this.card_id = card_id;
		this.username = username;
		this.password = password;
		this.balance = balance;
		this.mobile = mobile;
	}
	public Account() {
		super();
		// TODO Auto-generated constructor stub
	}
	
}

dao层代码:

package com.baizhi.dao;

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

import org.apache.ibatis.annotations.Param;

import com.baizhi.entity.Account;

public interface AccountDao {
		Account queryById(Integer id);
//		Account queryByUsernameAndPassword(
//				String username,
//				String password
//				);
		//另一种参数绑定
		Account queryByUsernameAndPassword(
				@Param(value = "username") String username,
				@Param(value = "password") String password
				);
		List<Account> queryByParam(Map<String, String> param); 
		//查询所有返回一个泛型List
		List<Account> queryAll();
		//模糊查询
		List<Account> queryByLikeMobile(String mobile);
		
		//根据对象绑定查Mobile
		Account queryByMobile(Account acc);
		
		void updateAccount(Account acc);
		void insertAccount(Account acc);
		void deleteAccount(Account acc);
}
<?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.baizhi.dao.AccountDao">
	
	<!-- 查询实现
		id:属性 对应接口定义的方法名
		resultType:指定返回值的类型(全限定名)
	
	 -->
	<select id="queryById" resultType="com.baizhi.entity.Account">
		select card_id,username,password,balance,mobile
		from accounts
		where card_id=#{id}
	</select>
	
	<select id="queryByUsernameAndPassword" resultType="com.baizhi.entity.Account">
		select card_id,username,password,balance,mobile
		from accounts
		<!-- where username=#{0} and password=#{1} -->
		where username=#{username} and password=#{password}
	</select>
	
	<select id="queryByParam" resultType="com.baizhi.entity.Account">
		select card_id,username,password,balance,mobile
		from accounts
		where username=#{name} and password=#{pwd}
	</select>
	
	<select id="queryByMobile" resultType="com.baizhi.entity.Account">
		select card_id,username,password,balance,mobile
		from accounts
		where mobile=#{mobile}
	</select>
	
	<select id="queryAll" resultType="com.baizhi.entity.Account">
		select card_id,username,password,balance,mobile
		from accounts
	</select>
	
	<select id="queryByLikeMobile" resultType="com.baizhi.entity.Account">
		select card_id,username,password,balance,mobile
		from accounts
	<!-- where mobile like '%174%' -->	
		where mobile like '%'||#{mobile}||'%'
	</select>
	
	<update id="updateAccount">
		update accounts set username=#{username},password=#{password},
		balance=#{balance},mobile=#{mobile}
		where card_id=#{card_id}
	</update>
	<!-- 第一种插入实现 -->
	<!-- <insert id="insertAccount">
		insert into accounts values(account_seq.nextval,#{username},#{password},#{balance},#{mobile})
	</insert> -->
	<!-- 第二种插入实现  添加成功后同时返回当前数据的主键值-->
	<insert id="insertAccount">
	<!-- 在执行前先查询生成主键 -->
	<selectKey keyProperty="card_id" resultType="java.lang.Integer" order="BEFORE">
		select account_seq.nextval from dual
	</selectKey>
		insert into accounts values(#{card_id},#{username},#{password},#{balance},#{mobile})
	</insert>
	<delete id="deleteAccount">
		delete from accounts where card_id=#{card_id}
	</delete>
</mapper>

util层封装代码:

package com.baizhi.util;

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;

import com.baizhi.dao.AccountDao;
import com.baizhi.entity.Account;

public class MybatisUtil {
	public static SqlSessionFactory factory;
	//静态初始代码块,书写只需要执行一次的操作,静态代码块的代码只在类加载的时候执行一次
	static {
		InputStream in = null;
		try {
			//读取核心配置文件mybatis-config.xml
			in = Resources.getResourceAsStream("mybatis-config.xml");
			//创建SqlSessionFactory
			factory = new SqlSessionFactoryBuilder().build(in);
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("初始化工厂失败");
		}finally {
			try {
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	//创建一个线程绑定对象
	private static ThreadLocal<SqlSession> tol=new ThreadLocal<SqlSession>();
	//返回一个SqlSession
	public static SqlSession opSession() {
		//先到当前线程取一下
		SqlSession sqlSession =tol.get();
		if(sqlSession==null) {
			//创建SqlSession
			sqlSession = factory.openSession();
			//绑定到当前线程
			tol.set(sqlSession);
		}
		return sqlSession;
	}
	
	//释放资源
	public static void close(){
		SqlSession sqlSession=tol.get();
		if(sqlSession!=null) { 
			sqlSession.close();
			tol.remove();//从当前线程移除
		}
	}
	
	//提交事务
	public static void commit() {
		SqlSession sqlSession=tol.get();
		if(sqlSession!=null) { 
			sqlSession.commit();
		}
	}
	//回滚事务
	public static void rollback() {
		SqlSession sqlSession=tol.get();
		if(sqlSession!=null) { 
			sqlSession.rollback();
		}
	}
}

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>
<!-- 编写mybatis的运行环境 -->
	<environments default="oracle">
		<environment id="oracle">
		<!-- 指定事务采用JDBC的方式管理 -->
			<transactionManager type="JDBC"></transactionManager>
			<!-- 使用mybatis提供的POOLED连接池 -->
			<dataSource type="POOLED">
				<property name="driver" value="oracle.jdbc.OracleDriver"/>
				<property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL"/>
				<property name="username" value="HR"/>
				<property name="password" value="hr"/>
			</dataSource>
		</environment>
	</environments>
	
	<!-- 注册mapper文件位置 -->
	<mappers>
		<!-- 对mapper标签注册一个mapper文件的位置:路径一定严格大小写 文件用斜杠,包用点 -->
		<mapper resource="com/baizhi/dao/AccountDaoMapper.xml"></mapper>
	
	
	</mappers>
	
</configuration>

test层Junit测试代码:

package com.baizhi.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.junit.jupiter.api.Test;

import com.baizhi.dao.AccountDao;
import com.baizhi.entity.Account;
import com.baizhi.util.MybatisUtil;

public class TestAccountDao {
	
	@Test
	public void testDeleteAccount() throws Exception {
		//1.读取核心配置文件mybatis-config.xml
		//InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		//2.创建SqlSessionFactory
		//SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		//3.创建SqlSession
		//SqlSession sqlSession = factory.openSession();
		/*
		 * 调用工具类获取SqlSession
		 */
		SqlSession sqlSession = MybatisUtil.opSession();
		//4.获取Dao接口实现类的对象
		AccountDao dao = sqlSession.getMapper(AccountDao.class);
		//5.调用方法
		Account acc=dao.queryById(10004);
		dao.deleteAccount(acc);
		MybatisUtil.commit();
		//6.释放资源
		MybatisUtil.close();
	}
	
	@Test
	public void testInsertAccount() throws Exception {
		//1.读取核心配置文件mybatis-config.xml
		//InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		//2.创建SqlSessionFactory
		//SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		//3.创建SqlSession
		//SqlSession sqlSession = factory.openSession();
		SqlSession sqlSession = MybatisUtil.opSession();
		//4.获取Dao接口实现类的对象
		AccountDao dao = sqlSession.getMapper(AccountDao.class);
		//5.调用方法
		Account acc = new Account(null,"Tim","123456",10.0,"1452688456");
		dao.insertAccount(acc);
		//sqlSession.commit();
		MybatisUtil.commit();
		//6.释放资源
		//sqlSession.close();
		MybatisUtil.close();
	}
	
	@Test
	public void testUpdateAccount() throws Exception {
		//1.读取核心配置文件mybatis-config.xml
		//InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		//2.创建SqlSessionFactory
		//SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		//3.创建SqlSession
		//SqlSession sqlSession = factory.openSession();
		SqlSession sqlSession = MybatisUtil.opSession();
		//4.获取Dao接口实现类的对象
		AccountDao dao = sqlSession.getMapper(AccountDao.class);
		//5.调用方法
		Account acc = dao.queryById(10003);
		acc.setBalance(90000.0);
		dao.updateAccount(acc);
		/*
		 * 增删改必须手动提交事务,不然mybatis会自动回滚
		 * 查询操作一定不要控制事务
		 */
		MybatisUtil.commit();
		//6.释放资源
		MybatisUtil.close();
	}
	
	@Test
	public void testQueryByLikeMobile() throws Exception {
		//1.读取核心配置文件mybatis-config.xml
		//InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		//2.创建SqlSessionFactory
		//SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		//3.创建SqlSession
		//SqlSession sqlSession = factory.openSession();
		SqlSession sqlSession = MybatisUtil.opSession();
		//4.获取Dao接口实现类的对象
		AccountDao dao = sqlSession.getMapper(AccountDao.class);
		//5.调用方法
		//List<Account> list=dao.queryByLikeMobile("");
		List<Account> list=dao.queryByLikeMobile("174");
		for (Account account : list) {
			System.out.println(account);
		}
		//6.释放资源
		MybatisUtil.close();
	}
	
	@Test
	public void testQueryAll() throws Exception {
		//1.读取核心配置文件mybatis-config.xml
		//InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		//2.创建SqlSessionFactory
		//SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		//3.创建SqlSession
		//SqlSession sqlSession = factory.openSession();
		//4.获取Dao接口实现类的对象
		SqlSession sqlSession = MybatisUtil.opSession();
		AccountDao dao = sqlSession.getMapper(AccountDao.class);
		//5.调用方法
		List<Account> list=dao.queryAll();
		for (Account account : list) {
			System.out.println(account);
		}
		//6.释放资源
		MybatisUtil.close();
	}
	
	
	@Test
	public void testQueryByMobile() throws Exception {
		//1.读取核心配置文件mybatis-config.xml
		//InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		//2.创建SqlSessionFactory
		//SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		//3.创建SqlSession
		//SqlSession sqlSession = factory.openSession();
		SqlSession sqlSession = MybatisUtil.opSession();
		//4.获取Dao接口实现类的对象
		AccountDao dao = sqlSession.getMapper(AccountDao.class);
		//5.调用方法
		Account acc = new Account();
		acc.setMobile("174852694");
		Account acc1=dao.queryByMobile(acc);
		System.out.println(acc1);
		//6.释放资源
		MybatisUtil.close();
	}
	
	@Test
	public void testQueryByParam() throws Exception {
		//1.读取核心配置文件mybatis-config.xml
		//InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		//2.创建SqlSessionFactory
		//SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		//3.创建SqlSession
		//SqlSession sqlSession = factory.openSession();
		SqlSession sqlSession = MybatisUtil.opSession();
		//4.获取Dao接口实现类的对象
		AccountDao dao = sqlSession.getMapper(AccountDao.class);
		//5.调用方法
		Map<String, String> param = new HashMap<String, String>();
		param.put("name","Jack");
		param.put("pwd","123456");
		List<Account> list = dao.queryByParam(param);
		for (Account account : list) {
			System.out.println(account);
		}
		//6.释放资源
		MybatisUtil.close();
	}
	
	
	@Test
	public void testQueryByUsernameAndPassword() throws Exception {
		//1.读取核心配置文件mybatis-config.xml
		//InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		//2.创建SqlSessionFactory
		//SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		//3.创建SqlSession
		//SqlSession sqlSession = factory.openSession();
		SqlSession sqlSession = MybatisUtil.opSession();
		//4.获取Dao接口实现类的对象
		AccountDao dao = sqlSession.getMapper(AccountDao.class);
		//5.调用方法
		Account acc = dao.queryByUsernameAndPassword("Jack","123456");
		System.out.println(acc);
		//6.释放资源
		MybatisUtil.close();
	}
	
	
	
	
	
	@Test
	public void testQueryById() throws Exception{
		//1.读取核心配置文件mybatis-config.xml
		//InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
		//2.创建SqlSessionFactory
		//SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
		//3.创建SqlSession
		//SqlSession sqlSession = factory.openSession();
		SqlSession sqlSession = MybatisUtil.opSession();
		//4.获取Dao接口实现类的对象
		AccountDao dao = sqlSession.getMapper(AccountDao.class);
		//5.调用方法
		Account acc = dao.queryById(10006);
		System.out.println(acc);
		//6.释放资源
		MybatisUtil.close();
	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值