Mybatis 是一个优秀的持久层框架,是对JDBC操作数据库的过程进行了封装.
create database mytest;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '匿名',
`age` int(11) NOT NULL,
`sex` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT '男',
`address` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL,
`email` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `email`(`email`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '匿名', 11, '男', '1111', '11111');
<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.itgroupId>
<artifactId>mybatis_leanartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<maven.compiler.source>8maven.compiler.source>
<maven.compiler.target>8maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.26version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>1.7.30version>
dependency>
dependencies>
project>
jdbc.properties文件,描述连接数据库的属性
jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mytest
jdbc.username = root
jdbc.password = 123456
mybatis-config.xml , mybatis 核心配置文件
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"/>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<environments default="test">
<environment id="test">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mapper/UserMapper.xml">mapper>
mappers>
configuration>
mapper/*.xml
报错,把*改成具体的mapper.xml文件名称,具体原因尚未明确package com.it.pojo;
public class User {
private long id;
private String name;
private int age;
private String sex;
private String address;
private String email;
public User(long id, String name, int age, String sex, String address, String email) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
this.address = address;
this.email = email;
}
public User() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
", email='" + email + '\'' +
'}';
}
}
package com.it.dao;
import com.it.pojo.User;
import java.util.Collection;
@Mapper
public interface UserDao {
Collection<User> findAll();
User findById(long id);
void save(User user);
void update(User user);
void delete(long id);
}
UserMapper.xml
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.it.dao.UserDao">
<select id="findAll" resultType="com.it.pojo.User">
select * from user
select>
<select id="findById" resultType="com.it.pojo.User">
select * from user where id = #{id}
select>
<insert id="save">
insert into user value(#{id},#{name},#{age},#{sex},#{address},#{email})
insert>
<update id="update">
update user set name = #{name} where id = #{id}
update>
<delete id="delete">
delete from user where id = #{id}
delete>
mapper>
package com.it.test;
import com.it.dao.UserDao;
import com.it.pojo.User;
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 java.io.IOException;
import java.util.Collection;
public class Test01 {
static SqlSessionFactoryBuilder builder =new SqlSessionFactoryBuilder();
static UserDao userDao;
public static void findAll(){
Collection<User> all = userDao.findAll();
System.out.println("查询所有结果");
System.out.println("---------------------------------");
for (User user:all){
System.out.println(user.toString());
}
}
public static void findById(){
User user = userDao.findById(1);
System.out.println("查询所有结果");
System.out.println("---------------------------------");
System.out.println(user.toString());
}
public static void save(){
User user = new User(3,"ls",22,"男","llll.","000000");
userDao.save(user);
System.out.println("新增数据"+user.toString()+"成功");
}
public static void update(){
User user = new User(2,"zhangs",22,null,"","");
userDao.update(user);
System.out.println("修改数据"+user.toString()+"成功");
}
public static void delete(){
userDao.delete(2);
System.out.println("删除成功");
}
public static void main(String[] args) {
SqlSession session=null;
SqlSessionFactory factory = null;
try {
factory = builder.build(Resources.getResourceAsStream("mybatis-config.xml"));
session = factory.openSession();
userDao = session.getMapper(UserDao.class);
System.out.println("============================");
findAll();
System.out.println("============================");
findById();
System.out.println("============================");
save();
findAll();
System.out.println("============================");
update();
findAll();
System.out.println("============================");
delete();
findAll();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (session!=null){
session.commit();
session.close();
}
}
}
}
修改dao层的代码,创建数据操作接口
package com.it.dao;
import com.it.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.Collection;
/**
* 使用注解执行sql
* @author ZRY
* @version 1.0
*/
public interface UserDao1 {
@Select("select * from user")
Collection<User> findAll();
@Select("select * from user where id = #{id}")
User findById(long id);
@Insert("insert into user value(#{id},#{name},#{age},#{sex},#{address},#{email})")
void save(User user);
@Update(" update user set name = #{name} where id=#{id}")
void update(User user);
@Delete("delete from user where id=#{id}")
void delete(long id);
}
修改核心配置文件,mybatis-config.xml
新增
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="jdbc.properties"/>
<environments default="test">
<environment id="test">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="dirver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mapper/UserMapper.xml">mapper>
<mapper class="com.it.dao.UserDao1"/>
mappers>
configuration>
package com.it.test;
import com.it.dao.UserDao;
import com.it.dao.UserDao1;
import com.it.pojo.User;
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 java.io.IOException;
import java.util.Collection;
public class Test02 {
static SqlSessionFactoryBuilder builder =new SqlSessionFactoryBuilder();
static UserDao1 userDao1;
public static void findAll(){
Collection<User> all = userDao1.findAll();
System.out.println("查询所有结果");
System.out.println("---------------------------------");
for (User user:all){
System.out.println(user.toString());
}
}
public static void findById(){
User user = userDao1.findById(1);
System.out.println("查询所有结果");
System.out.println("---------------------------------");
System.out.println(user.toString());
}
public static void save(){
User user = new User(2,"ls",22,"男","llll","");
userDao1.save(user);
System.out.println("新增数据"+user.toString()+"成功");
}
public static void update(){
User user = new User(3,"zhangs",22,null,"","");
userDao1.update(user);
System.out.println("修改数据"+user.toString()+"成功");
}
public static void delete(){
userDao1.delete(2);
System.out.println("删除成功");
}
public static void main(String[] args) {
SqlSession session=null;
SqlSessionFactory factory = null;
try {
factory = builder.build(Resources.getResourceAsStream("mybatis-config.xml"));
session = factory.openSession();
userDao1 = session.getMapper(UserDao1.class);
System.out.println("============================");
findAll();
System.out.println("============================");
findById();
System.out.println("============================");
save();
findAll();
System.out.println("============================");
update();
findAll();
System.out.println("============================");
delete();
findAll();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (session!=null){
session.commit();
session.close();
}
}
}
}