Mybatis通过接口的方式实现增删改查
导入jar包
【mybatis】

【oracle】

生成数据库

1、添加Mybatis的配置文件mybatis-config.xml
在src目录下创建一个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>
<properties resource="db.properties"></properties>
<typeAliases>
<package name="com.model"/>
</typeAliases> <environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="url" value="${jdbc.url}"/>
<property name="driver" value="${jdbc.driverClass}"/>
</dataSource> </environment>
</environments> <mappers>
<!-- <mapper resource="com/dao/UserMapper.xml"/> -->
<package name="com.dao"/>
</mappers>
</configuration>
db.properties如下:
jdbc.username=root
jdbc.password=123
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.driverClass=oracle.jdbc.OracleDriver
2、定义表所对应的实体类,如下图所示:

package com.model;
// Generated 2017-4-19 10:19:42 by Hibernate Tools 5.2.0.CR1 import java.math.BigDecimal; import org.apache.ibatis.type.Alias; /**
* TestId generated by hbm2java
*/
public class TestId { private BigDecimal id;
private String username;
private String password; public TestId() {
} public TestId(BigDecimal id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
} public BigDecimal getId() {
return this.id;
} public void setId(BigDecimal id) {
this.id = id;
} public String getUsername() {
return this.username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return this.password;
} public void setPassword(String password) {
this.password = password;
} public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof TestId))
return false;
TestId castOther = (TestId) other; return ((this.getId() == castOther.getId())
|| (this.getId() != null && castOther.getId() != null && this.getId().equals(castOther.getId())))
&& ((this.getUsername() == castOther.getUsername()) || (this.getUsername() != null
&& castOther.getUsername() != null && this.getUsername().equals(castOther.getUsername())))
&& ((this.getPassword() == castOther.getPassword()) || (this.getPassword() != null
&& castOther.getPassword() != null && this.getPassword().equals(castOther.getPassword())));
} public int hashCode() {
int result = 17; result = 37 * result + (getId() == null ? 0 : this.getId().hashCode());
result = 37 * result + (getUsername() == null ? 0 : this.getUsername().hashCode());
result = 37 * result + (getPassword() == null ? 0 : this.getPassword().hashCode());
return result;
} @Override
public String toString() {
return "TestId [id=" + id + ", username=" + username + ", password=" + password + "]";
} }
package com.model;
import java.util.Date;
public class TestInfo {
private Integer ids;
private TestId testId;
private String address;
private Date birthday;
public Integer getIds() {
return ids;
}
public void setIds(Integer ids) {
this.ids = ids;
}
public TestId getTestId() {
return testId;
}
public void setTestId(TestId testId) {
this.testId = testId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public TestInfo(Integer ids, TestId testId, String address, Date birthday) {
super();
this.ids = ids;
this.testId = testId;
this.address = address;
this.birthday = birthday;
}
public TestInfo() {
super();
}
@Override
public String toString() {
return "TestInfo [ids=" + ids + ", testId=" + testId + ", address=" + address + ", birthday=" + birthday + "]";
}
}
3、定义操作test表的sql映射文件

UserInfoMapper.java接口如下:
package com.dao;
import java.util.List;
import com.model.TestInfo;
public interface UserInfoMapper {
public List<TestInfo> select();
}
UserMapper.java接口如下:
package com.dao; import java.util.List;
import java.util.Map; import com.model.TestId; public interface UserMapper {
public Integer add(TestId ti); public Integer delete(Integer id); public Integer update(TestId ti); public TestId select(Integer id); public List<TestId> selectlist(Map<String, Object> map);
}
UserInfoMapper.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"> <mapper namespace="com.dao.UserInfoMapper">
<!-- 一对一级连查询方法1 -->
<resultMap type="testInfo" id="userslist">
<id property="ids" column="ids"/> <result property="testId.id" column="id"/>
<result property="testId.username" column="username"/>
<result property="testId.password" column="password"/> <result property="address" column="address"/>
<result property="birthday" column="birthday"/>
</resultMap>
<!-- 一对一级连查询方法2 -->
<resultMap type="testInfo" id="userlist">
<association property="testId" column="id" select="com.dao.UserMapper.select"></association>
</resultMap> <select id="select" resultMap="userslist">
select * from testinfo ti left join test t on ti.id=t.id
</select>
</mapper>
UserMapper.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"> <mapper namespace="com.dao.UserMapper"> <resultMap type="testId" id="users"></resultMap> <insert id="add" parameterType="testId">
insert into test values(sq_mybatis.nextval,#{username},#{password})
</insert> <delete id="delete" parameterType="Integer">
delete test t where t.id=#{id}
</delete> <update id="update" parameterType="testId">
update test t set t.username=#{username},t.password=#{password} where t.id=#{id}
</update> <select id="select" parameterType="Integer" resultType="testId">
select * from test t where t.id=#{id}
</select> <select id="selectlist" parameterType="Map" resultMap="users">
select * from test t where t.username like #{username} and t.password like #{password}
</select>
</mapper>
4、创建一个MybatisUtil的和Junit的类,来进行测试

MybatisUtil.java如下:
package com.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; /**
* mybatis工具类
* @author Administrator
*
*/
public class MybatisUtil {
private static SqlSessionFactory ssf;
private static SqlSession ss; /**
* 获取mybatis核心sqlsessionfactory
* @return
*/
private static SqlSessionFactory getSqlSessionFctory(){
InputStream it = null; try {
it = Resources.getResourceAsStream("mybatis-config.xml");
ssf= new SqlSessionFactoryBuilder().build(it);
ss=ssf.openSession();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return ssf;
}
/**
* 获取sqlsession
* @return
*/
public static SqlSession getSqlSession(){
ss= getSqlSessionFctory().openSession();
return ss; }
public static void main(String[] args){
System.out.println(getSqlSession());
}
}
Junit.java如下:
package com.util; import static org.junit.Assert.*; import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.dao.UserMapper;
import com.model.TestId; public class Junit { private SqlSession ss;
private UserMapper um; @Before
public void setUp() throws Exception {
ss=MybatisUtil.getSqlSession();
um=ss.getMapper(UserMapper.class);
} @After
public void tearDown() throws Exception {
ss.commit();
ss.close();
} public void test() {
TestId ti = new TestId();
ti.setUsername("张张柳");
ti.setPassword("443221");
//int i =ss.insert("com.dao.UserMapper.add",ti);
int i=um.add(ti);
System.out.println(i);
} public void test1(){
int i = um.delete(401);
System.out.println(i);
} public void test2(){
TestId ti = new TestId();
ti.setId(new BigDecimal(441));
ti.setUsername("张张柳2");
ti.setPassword("443221"); um.update(ti);
} public void test3(){
TestId ti =um.select(441);
System.out.println(ti);
}
@Test
public void tes4(){
Map<String, Object> map = new HashMap<String, Object>();
map.put("username", "张%");
map.put("password", "%2%");
List<TestId> list =um.selectlist(map);
for(TestId ti:list){
System.out.println(ti);
} } }
Junit2.java如下:
package com.util; import static org.junit.Assert.*; import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.dao.UserInfoMapper;
import com.dao.UserMapper;
import com.model.TestId;
import com.model.TestInfo; public class Junit2 { private SqlSession ss;
private UserInfoMapper um; @Before
public void setUp() throws Exception {
ss=MybatisUtil.getSqlSession();
um=ss.getMapper(UserInfoMapper.class);
} @After
public void tearDown() throws Exception {
ss.commit();
ss.close();
} @Test
public void test() {
List<TestInfo> list = um.select();
for(TestInfo ti :list){
System.out.println(ti);
}
} }
Mybatis通过接口的方式实现增删改查的更多相关文章
- MyBatis学习(三)MyBatis基于动态代理方式的增删改查
1.前言 上一期讲到MyBatis-Statement版本的增删改查.可以发现.这种代码写下来冗余的地方特别多.写一套没啥.如果涉及到多表多查询的时候就容易出现问题.故.官方推荐了一种方法.即MyBa ...
- 02.Mybatis的动态代理方式实现增删改查
动态代理的方式实现增删改查: 通过约定的方式定位sql语句 约定 > 配置文件 > 硬编码 约定的目标是省略掉通过硬编码的方式定位sql的代码,通过接口直接定位出sql语句,以下代码为通过 ...
- Spring Boot入门系列(十八)整合mybatis,使用注解的方式实现增删改查
之前介绍了Spring Boot 整合mybatis 使用xml配置的方式实现增删改查,还介绍了自定义mapper 实现复杂多表关联查询.虽然目前 mybatis 使用xml 配置的方式 已经极大减轻 ...
- Mybatis实现简单的CRUD(增删改查)原理及实例分析
Mybatis实现简单的CRUD(增删改查) 用到的数据库: CREATE DATABASE `mybatis`; USE `mybatis`; DROP TABLE IF EXISTS `user` ...
- Android-Sqlite-OOP方式操作增删改查
之前写的数据库增删改查,是使用SQL语句来实现的,Google 就为Android开发人员考虑,就算不会SQL语句也能实现增删改查,所以就有了OOP面向对象的增删改查方式 其实这种OOP面向对象的增删 ...
- Mybatis学习总结(二)—使用接口实现数据的增删改查
在这一篇中,让我们使用接口来实现一个用户数据的增删改查. 完成后的项目结构如下图所示: 在这里,person代表了一个用户的实体类.在该类中,描述了相关的信息,包括id.name.age.id_num ...
- Mybatis学习笔记之---CRUD(增删改查)
Mybatis的CRUD(增删改查) 1.pom.xml <dependencies> <dependency> <groupId>junit</groupI ...
- ssm框架(Spring Springmvc Mybatis框架)整合及案例增删改查
三大框架介绍 ssm框架是由Spring springmvc和Mybatis共同组成的框架.Spring和Springmvc都是spring公司开发的,因此他们之间不需要整合.也可以说是无缝整合.my ...
- MyBatis初级实战之二:增删改查
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
随机推荐
- IOS UIActivityIndicatorView动画
● 是一个旋转进度轮,可以用来告知用户有一个操作正在进行中,一般 用initWithActivityIndicatorStyle初始化 ● 方法解析: ● - (void)startAnimating ...
- 【BZOJ1064】[NOI2008] 假面舞会(图上DFS)
点此看题面 大致题意:有\(k\)种面具(\(k\)是一个未知数且\(k≥3\),每种面具可能有多个),已知戴第\(i\)种面具的人能看到第\(i+1\)种面具上的编号,特殊的,戴第\(k\)种面具的 ...
- ThreadLocal为什么要用WeakReference
先上一张图看一下ThreadLocal的内部结构,每个Thread对象内部都维护了一个ThreadLocal.ThreadLocalMap 我们在上图看到的就是三个Thread对象内部格子的Threa ...
- 更新MySQL数据库( java.sql.SQLException: No value specified for parameter 1) 异常 解决方法
package com.swift; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatemen ...
- vue框架初学习的基本指令
学习地址:<ahref="https: cn.vuejs.="" org="" "="" targe ...
- STL笔记(こ)--删除数组中重复元素
使用STL中的Unique函数: #include<bits/stdc++.h> using namespace std; void fun(int &n) //配套for_eac ...
- 散列表的ASL计算
题目: 已知关键字序列为{30,25,72,38,8,17,59},设散列表表长为15.散列函数是H(key)=key MOD 13,处理冲突的方法为二次探测法Hi= ( H(key) + di )m ...
- 【C++学习笔记】强大的算法——spfa
spfa的定义 PFA算法的全称是:Shortest Path Faster Algorithm,用于求单源最短路,由西南交通大学段凡丁于1994年发表.当给定的图存在负边时,Dijkstra算法就无 ...
- 微信小游戏 demo 飞机大战 代码分析(四)(enemy.js, bullet.js, index.js)
微信小游戏 demo 飞机大战 代码分析(四)(enemy.js, bullet.js, index.js) 微信小游戏 demo 飞机大战 代码分析(一)(main.js) 微信小游戏 demo 飞 ...
- PHP 作用域