mybatis是对jdbc的封装,开源的持久层框架,简化增删改查
封装了获取连接,执行sql,关闭连接
封装了sql参数的设置
封装了结果集中记录映射成实体对象
mybatis自带数据库连接池
这次测试的项目目录。这里用的maven创建的一简单的项目里面Mapper.xml可以不用管,不同的数据表的操作可以写在不同的Mapper.xml文件中,这里谷咕咕用的User表的操作,下面也只展示UserMapper.xml。
1.pom.xml
创建完项目,导入mybatis以来的架包
maven项目在pom.xml中添加
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.haishigroupId>
<artifactId>MyBatisartifactId>
<version>0.0.1-SNAPSHOTversion>
<packaging>jarpackaging>
<name>MyBatisname>
<url>http://maven.apache.orgurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.40version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.3.3.RELEASEversion>
dependency>
dependencies>
project>
2.mybatis-config.xml
添加mybatis核心配置文件,设置连接数据库的基本属性
<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/project"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/haishi/UserMapper.xml"/>
mappers>
configuration>
3.TestCase.java
编写测试类,检测是否数据库连接正常。
package Test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.List;
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.Before;
import org.junit.Test;
import com.haishi.User;
public class TestCase {
private SqlSession session;
@Before
public void init() throws IOException {
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
InputStream is=Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory=builder.build(is);
session=factory.openSession();
}
@Test
public void test1() {
Connection conn =session.getConnection();
System.out.println(conn);
// User u=new User();
// u.setUser_name("zwk");
// u.setPwd("123");
// u.setPhone("1234567899");
// u.setEmail("[email protected]");
// u.setTime(new Timestamp(System.currentTimeMillis()));
// session.insert("test.save",u);
/**
* 手动提交事务
*/
// session.commit();
// session.close();
}
User.java
实体类基于操作数据表的字段设置,就是一些set,get,toString的方法。
还是给大家,看一下谷咕咕这次的操作的user_t的表结构。
package com.haishi;
import java.sql.Timestamp;
public class User {
private Integer id;
private String user_name;
private String pwd;
private String phone;
private String email;
private Timestamp time;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Timestamp getTime() {
return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
@Override
public String toString() {
return "User [id=" + id + ", user_name=" + user_name + ", pwd=" + pwd + ", phone=" + phone + ", email=" + email
+ "]";
}
}
编写实体类
UserMapper.xml
这个文件是具体sql操作的地方每一个sql都写了注释,应该比较简单。
需要注意的是,UserMapper.xml需要在mybatis-config.xml配置sql映射文件的位置。细心的同学应该注意到前面的mybatis-config.xml中有,这里谷咕咕还是贴个图片看一下。
<mapper namespace="test">
<insert id="save" parameterType="com.haishi.User">
INSERT INTO user_t VALUES(null,#{user_name},#{pwd},#{phone}
,#{email},#{time})
insert>
<select id="findall" resultType="com.haishi.User">
select * from user_t
select>
<select id="findById" parameterType="int" resultType="com.haishi.User">
select * from user_t where id=#{id}
select>
<update id="update" parameterType="com.haishi.User">
update user_t set phone=#{phone},email=#{email} where user_name=#{user_name}
update>
<delete id="delete" parameterType="int">
delete from user_t where id=#{id}
delete>
mapper>
TestCase.java
测试类,这里谷咕咕把所有的,增删改查的测试类都贴上了。
大家想测试的只要解开对应的tset()方法前的注释就可以了。
下面演示一下增加。
package Test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Timestamp;
import java.util.List;
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.Before;
import org.junit.Test;
import com.haishi.User;
public class TestCase {
private SqlSession session;
@Before
public void init() throws IOException {
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
InputStream is=Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory=builder.build(is);
session=factory.openSession();
}
@Test
public void test1() {
Connection conn =session.getConnection();
System.out.println(conn);
User u=new User();
u.setUser_name("zwk");
u.setPwd("123");
u.setPhone("1234567899");
u.setEmail("[email protected]");
u.setTime(new Timestamp(System.currentTimeMillis()));
session.insert("test.save",u);
/**
* 手动提交事务
*/
session.commit();
session.close();
}
// @Test
public void test2() {
List<User> users=session.selectList("test.findall");
System.out.println(users);
System.out.println(users.size());
}
// @Test
public void test3() {
User u=session.selectOne("test.findById",1003);
System.out.println(u);
session.close();
}
// @Test
public void test4() {
User u=session.selectOne("test.findById", 1003);
u.setPhone("change123456123");
session.update("test.update",u);
session.commit();
session.close();
}
// @Test
public void test5() {
session.delete("test.delete",1005);
session.close();
}
}
解开一个test注释,其他的test必须要注释,刷新一下,插入成功。
比较需要大家,理解的可能就是UserMapper.xml文件中的
parameterType设置插入对象的类型
根据id查用户的信息,就需要用户传入id,所以需要parameterType=“int”,同理要是按名字查询,就是String。
resultType设置返回结果集的类型
这里谷咕咕返回的都是user对象,查询需要返回,但是插入和修改都没有返回类型,这个也比较好理解。
如果对大家有用,记得点赞哦