1. 创建数据库
小编已经在数据库中创建了用户数据库
接下来我们创建学生表
USER `user`;
CREATE TABLE `student`(
`uid` INT(12) NOT NULL AUTO_INCREMENT,
`uname` VARCHAR(32) NOT NULL,
`password` INT(16) NOT NULL,
`birthday` DATE NOT NULL,
PRIMARY KEY(`uid`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
创建成功如下
2. 配置pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>day01_eesy_02mybatis_annotation</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
</dependencies>
</project>
在创建项目的时候,只需要记得导入junit,apectjweaver,sql-connector-java,spring-test,spring-context,spring-context,spring-tx,spring-jdbc,commons-dbutilsjar包
即可
3. 注册数据库的驱动器
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/user
jdbc.username=root
jdbc.password=root
4. 配置log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
5. 配置文件
<?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>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql的环境-->
<environment id="mysql">
<!--配置连接池-->
<transactionManager type="JDBC"></transactionManager>
<!--使用连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/user"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--配置映射文件的位置-->
<mappers>
<mapper resource="com/ithemo/dao/StudentDao.xml"></mapper>
</mappers>
</configuration>
6. 创建实体类
package com.ithemo.domain;
import java.io.Serializable;
import java.util.Date;
/**
* 账户的实体类
*/
public class Student implements Serializable {
private Integer uid;
private String uname;
private Float password;
private Date birthday;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public Float getPassword() {
return password;
}
public void setPassword(Float password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Student{" +
"uid=" + uid +
", uname='" + uname + '\'' +
", password=" + password +
", birthday=" + birthday +
'}';
}
}
7. 创建持久层接口
package com.itheima.dao;
import com.itheima.domain.Student;
/**
* 账户的持久层接口
*/
public interface StudentDao {
/**
* 根据Id查询账户
* @param uid
* @return
*/
Student findStudentById(Integer uid);
/**
* 根据名称查询账户
* @param
* @return
*/
Student findStudnetByUname(String StudnetUname);
/**
* 更新账户
* @param student
*/
void updateStudent(Student student);
/**
* 根据id删除账户
* @param uid
* @return
*/
void deteleId(Integer uid);
}
查询一个
创建持久层接口的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
namespace="com.ithemo.dao.StudentDao">
<select id="findStudentById" parameterType="INT" resultType="com.ithemo.domain.Student">
select * from student where uid=#{uid}
</select>
</mapper>
测试类
package com.ithemo.test;
import com.ithemo.dao.StudentDao;
import com.ithemo.domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;
/**
* 使用Junit单元测试:测试我们的配置
*/
public class StudentServiceTest {
@Test
public void findStudentById() throws Exception {
//1.读取配置文件,生产字节输入流
InputStream in = Resources.getResourceAsStream("MapConfig.xml");
//2.获取SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//4.获取代理对象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
//5.执行查询
Student studentById = mapper.findStudentById(1);
System.out.println(studentById);
}
}
结果截图
模糊查询
创建持久层接口的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
namespace="com.ithemo.dao.StudentDao">
<select id="findStudnetByUname" parameterType="String" resultType="com.ithemo.domain.Student">
select * from student where uname like #{uname}
</select>
</mapper>
测试类
package com.ithemo.test;
import com.ithemo.dao.StudentDao;
import com.ithemo.domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;
import java.util.List;
/**
* 使用Junit单元测试:测试我们的配置
*/
public class StudentServiceTest {
@Test
public void findStudentById() throws Exception {
//1.读取配置文件,生产字节输入流
InputStream in = Resources.getResourceAsStream("MapConfig.xml");
//2.获取SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//4.获取代理对象
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
//5.根据名称查询
List<Student> studnetByUname = studentDao.findStudnetByUname("%花%");
for (Student user:studnetByUname) {
System.out.println(user);
}
}
}
结果截图
另一种模糊查询
创建持久层接口的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
namespace="com.ithemo.dao.StudentDao">
<select id="findStudnetByUname" parameterType="String" resultType="com.ithemo.domain.Student">
select * from student where uname like '%${value}%'
</select>
</mapper>
测试类
package com.ithemo.test;
import com.ithemo.dao.StudentDao;
import com.ithemo.domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;
import java.util.List;
/**
* 使用Junit单元测试:测试我们的配置
*/
public class StudentServiceTest {
@Test
public void findStudentById() throws Exception {
//1.读取配置文件,生产字节输入流
InputStream in = Resources.getResourceAsStream("MapConfig.xml");
//2.获取SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//4.获取代理对象
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
//5.根据名称查询
List<Student> student = studentDao.findStudnetByUname("花");
for (Student student1:student) {
System.out.println(student1);
}
}
}
结果截图
保存操作
创建持久层接口的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
namespace="com.ithemo.dao.StudentDao">
<insert id="updateStudent" parameterType="com.ithemo.domain.Student">
insert into student(uid,uname,password,birthday)values(#{uid},#{uname},#{password},#{birthday})
</insert>
</mapper>
测试类
package com.ithemo.test;
import com.ithemo.dao.StudentDao;
import com.ithemo.domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;
import java.util.Date;
/**
* 使用Junit单元测试:测试我们的配置
*/
public class MaybatisTest {
@Test
public void findStudentById() throws Exception {
Student student=new Student();
student.setUid(7);
student.setUsername("理想");
student.setPassword(123400F);
student.setBirthday(new Date());
//1.读取配置文件,生产字节输入流
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//4.获取代理对象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
//5.执行查询
mapper.updateStudent(student);
sqlSession.commit();
System.out.println(student);
}
}
结果截图
删除操作
创建持久层接口的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
namespace="com.ithemo.dao.StudentDao">
<delete id="deteleId" parameterType="java.lang.Integer" >
delete from student where uid=#{uid}
</delete>
</mapper>
测试类
package com.ithemo.test;
import com.ithemo.dao.StudentDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;
/**
* 使用Junit单元测试:测试我们的配置
*/
public class MaybatisTest {
@Test
public void findStudentById() throws Exception {
//1.读取配置文件,生产字节输入流
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2.获取SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//4.获取代理对象
StudentDao mapper = sqlSession.getMapper(StudentDao.class);
//5.执行查询
mapper.deteleId(7);
sqlSession.commit();
}
}
结果截图