maven项目下添加mbatis和mysql的依赖包:
pom.xml
4.0.0
com.lks
mybatis-demo
1.0-SNAPSHOT
org.mybatis
mybatis
3.4.5
mysql
mysql-connector-java
8.0.12
org.testng
testng
6.14.3
test
连接数据库,创建简单的users表:
sql语句
create database mybatis_demo;
use mybatis_demo;
CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(20), age INT, county VARCHAR(10))ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO users(name, age, county) VALUES('李寻欢', 30, '中国');
INSERT INTO users(name, age, county) VALUES('美国队长', 27, '美国');
创建User实体类实现序列化:
User.java
package com.lks.domain;
import java.io.Serializable;
/**
* Created by likaisong on 2019/2/24.
*/
public class User implements Serializable {
private int id;
private String name;
private int age;
private String county;
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getCounty() {
return county;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setCounty(String county) {
this.county = county;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + ", county=" + county + "]";
}
}
mybatis的配置文件:
mybatis-config.xml
数据库操作的配置文件:
mapper.xml
insert into users (id,name,age,county)
values (#{id},#{name},#{age},#{county})
update users set name = #{name} where id = #{id}
delete from users where id = #{id}
pom.xml引入TestNg的依赖包,实现增删该查的测试:
TestMain.Java
package com.lks.test;
import com.lks.domain.User;
import com.lks.mapper.UserMapper;
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.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by likaisong on 2019/2/24.
*/
public class TestMain {
private static SqlSession getSqlSession(String resource){
if (resource == null || "".equals(resource)){
return null;
}
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
return session;
}
@Test
public static void testSelectByXml(){
String resource = "mybatis-config.xml";
SqlSession session = getSqlSession(resource);
try {
String statement = "userMapper.getUser";
User user = session.selectOne(statement, 2);
System.out.println(user);
} finally {
session.close();
}
}
@Test
public static void testInsertByXml(){
String resource = "mybatis-config.xml";
SqlSession session = getSqlSession(resource);
try {
String statement = "userMapper.insertUser";
User user = new User();
user.setName("阿飞");
user.setAge(20);
user.setCounty("中国");
session.insert(statement, user);
session.commit();
System.out.println("插入数据后返回的自增ID:" + user.getId());
} finally {
session.close();
}
}
@Test
public static void testUpdateByXml(){
String resource = "mybatis-config.xml";
SqlSession session = getSqlSession(resource);
try {
String statement = "userMapper.updateUser";
User user = new User();
user.setId(1);
user.setName("小李飞刀");
session.update(statement, user);
session.commit();
} finally {
session.close();
}
}
@Test
public static void testDeleteByXml(){
String resource = "mybatis-config.xml";
SqlSession session = getSqlSession(resource);
try {
//先增加一条数据
String insertStatement = "userMapper.insertUser";
User user = new User();
user.setName("阿飞");
user.setAge(20);
user.setCounty("中国");
session.insert(insertStatement, user);
System.out.println("插入数据后返回的自增ID:" + user.getId());
//再删掉刚刚加的数据
String deleteStatement = "userMapper.deleteUser";
session.delete(deleteStatement, user.getId());
session.commit();
} finally {
session.close();
}
}
}
mybatis配置文件:
mybatis-annotation-config.xml
映射Mapper接口:
package com.lks.mapper;
import com.lks.domain.User;
import org.apache.ibatis.annotations.*;
/**
* Created by likaisong on 2019/2/24.
*/
public interface UserMapper {
@Select("select * from users where id=#{id}")
User getUser(int id);
@Update("update users set name = #{name} where id = #{id}")
void updateUser(User user);
@Insert("insert into users (id,name,age,county) values (#{id},#{name},#{age},#{county})")
@Options(useGeneratedKeys=true, keyProperty="id")
void insertUser(User user);
@Delete("delete from users where id = #{id}")
void deleteUser(int id);
}
TestMain类中新增test方法:
TestMain.java
package com.lks.test;
import com.lks.domain.User;
import com.lks.mapper.UserMapper;
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.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by likaisong on 2019/2/24.
*/
public class TestMain {
private static SqlSession getSqlSession(String resource){
if (resource == null || "".equals(resource)){
return null;
}
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
return session;
}
@Test
public static void testSelectByAnnotation(){
String resource = "mybatis-annotation-config.xml";
SqlSession session = getSqlSession(resource);
try {
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.getUser(1);
System.out.println(user);
} finally {
session.close();
}
}
@Test
public static void testUpdateByAnnotation(){
String resource = "mybatis-annotation-config.xml";
SqlSession session = getSqlSession(resource);
try {
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User();
user.setId(2);
user.setName("钢铁侠");
mapper.updateUser(user);
session.commit();
} finally {
session.close();
}
}
@Test
public static void testInsertByAnnotation(){
String resource = "mybatis-annotation-config.xml";
SqlSession session = getSqlSession(resource);
try {
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User();
user.setName("阿飞");
user.setAge(20);
user.setCounty("中国");
mapper.insertUser(user);
session.commit();
System.out.println("插入数据后返回的自增ID:" + user.getId());
} finally {
session.close();
}
}
@Test
public static void testDeleteByAnnotation(){
String resource = "mybatis-annotation-config.xml";
SqlSession session = getSqlSession(resource);
try {
//先添加一条数据
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User();
user.setName("阿飞");
user.setAge(20);
user.setCounty("中国");
mapper.insertUser(user);
System.out.println("插入数据后返回的自增ID:" + user.getId());
//再删除刚加的数据
mapper.deleteUser(user.getId());
session.commit();
} finally {
session.close();
}
}
}
使用对于给定语句能够合理描述参数和返回值的接口(比如说UserMapper.class),你现在不但可以执行更清晰和类型安全的代码,而且还不用担心易错的字符串字面值以及强制类型转换。使用注解的方式还有很多优势,首先它不是基于字符串常量的,就会更安全;其次,如果你的 IDE 有代码补全功能,那么你可以在有了已映射 SQL 语句的基础之上利用这个功能。
项目地址:[email protected]:kaisongli/mybatis-demo.git