要求:在熟悉MySQL、Eclipse或MyEclipse开发环境基础上,创建一个学生表,使用Mybatis技术实现对学生对象的增删改查操作,其中查询包括根据学生ID查询、根据名字的模糊查找和通过姓名和住址的组合查询(姓名和住址可以同时给出也可以单独给出)。
注:Mybatis相当于Dao,可以对数据库中的数据进行增删改查操作,将数据库数据和java对象进行相互映射。
1、创建一个数据库,在该数据库中创建一个students的表,并插入三条数据:
2、导入相关的jar包(14个):如下图
3、在src下创建一个po包:编写持久化类Students
package com.tyut.po;
public class Students {
private int id;
private String name;
private int age;
private String gender;
private String number;
private String address;
private int status;
public int getId() {
return id;
}
public void setId(int 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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
@Override
public String toString(){
return "Student [id="+id+",name="+name+",age="+age+",gender="+gender+"," +
"number="+number+",address="+address+",status="+status+"]";
}
}
4、创建一个mapper包,编写持久化对象和数据库之间的映射文件:StudentsMapper.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">
<!-- namespace表示命名空间 -->
<mapper namespace="com.tyut.mapper.StudentsMapper">
<!-- 根据学生编号获取学生信息 精确查找 -->
<select id="findStudentById" parameterType="Integer"
resultType="com.tyut.po.Students">
select * from students where id=#{id}
</select>
<!-- 模糊查找 -->
<select id="findStudentByName" parameterType="String"
resultType="com.tyut.po.Students">
select * from students where name like '%${value}%'
</select>
<!-- 姓名和地址的组合查询 -->
<select id="findStudentByNameAndAddress" parameterType="com.tyut.po.Students"
resultType="com.tyut.po.Students">
select * from students where name=#{name} and address=#{address}
</select>
<!-- 插入一条数据 -->
<insert id="addStudent" parameterType="com.tyut.po.Students">
insert into students(name,age,gender,number,address,status)
values(#{name},#{age},#{gender},#{number},#{address},#{status})
</insert>
<!-- 更新学生信息 -->
<update id="updateStudent" parameterType="com.tyut.po.Students">
update students set name=#{name},age=#{age},gender=#{gender},number=#{number},address=#{address},status=#{status}
where id=#{id}
</update>
<!-- 删除学生信息 -->
<delete id="deleteStudent" parameterType="Integer">
delete from students where id=#{id}
</delete>
</mapper>
5、在src下,编写Mybatis的配置文件mybatis-config.xml:
(1)配置数据库环境
(2)加载映射文件到Mybatis框架中
<?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>
<!-- 1 配置数据库环境,默认环境为mysql -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db_jyf"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 2 配置映射的位置 ,加载映射文件-->
<mappers>
<mapper resource="com/tyut/mapper/StudentsMapper.xml" />
</mappers>
</configuration>
6、在src下,编写log4j.properties文件,用于将日志信息输出到控制台
(使用JUtil4测试执行@Test)
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.tyut=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
7、创建一个test测试包,编写测试文件MybatisTest:
package com.tyut.test;
import java.io.IOException;
import java.io.InputStream;
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.Test;
import com.tyut.po.Students;
public class MybatisTest {
//查询学生(精确查询用ID查询)
@Test
public void findStudentById() throws IOException{
//读取配置文件;
String resource="mybatis-config.xml";
//将配置文件转化为输入流对象;
InputStream inputStream=Resources.getResourceAsStream(resource);
//通过配置文件构建了SqlSessionFactory对象;
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
//得到SqlSession对象;
SqlSession sqlSession=sqlSessionFactory.openSession();
//用sqlSession执行映射文件中的select语句,返回值为Students对象;
Students student=sqlSession.selectOne("com.tyut.mapper.StudentsMapper.findStudentById",1);
System.out.println(student.toString());
sqlSession.close();
}
//查询学生(模糊查询用名字查询)
@Test
public void findStudentByName() throws IOException{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
List<Students> student=sqlSession.selectList("com.tyut.mapper.StudentsMapper.findStudentByName",'c');
for(Students students:student){
System.out.println(students);
}
sqlSession.close();
}
//组合查询(用名字和地址组合查询)
@Test
public void findStudentByNameAndAddress() throws IOException{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
Students student=new Students();
student.setAddress("北京");
student.setName("jack");
Students students=sqlSession.selectOne("com.tyut.mapper.StudentsMapper.findStudentByNameAndAddress", student);
System.out.println(students);
}
//添加学生
@Test
public void addStudent() throws IOException{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
Students student=new Students();
student.setName("jinyifei");
student.setAge(20);
student.setGender("男");
student.setAddress("山西");
student.setNumber("13866666");
student.setStatus(6);
int row=sqlSession.insert("com.tyut.mapper.StudentsMapper.addStudent",student);
if(row!=0){
System.out.println("添加成功了"+row+"条数据!");
}else{
System.out.println("添加失败!");
}
sqlSession.commit();//比其他操作多了一条提交操作;
sqlSession.close();
}
// 更新学生信息
@Test
public void updateStudent() throws IOException{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
Students student=new Students();
student.setName("jinyifei");
student.setAge(19);
student.setGender("男");
student.setAddress("成都");
student.setNumber("13888888");
student.setStatus(8);
student.setId(8);
int row=sqlSession.update("com.tyut.mapper.StudentsMapper.updateStudent",student);
if(row!=0){
System.out.println("有"+row+"条学生信息更新成功!");
}else{
System.out.println("更新失败");
}
sqlSession.commit();//记得提交;
sqlSession.close();
}
//删除学生信息
@Test
public void deleteStudent() throws IOException{
String resource="mybatis-config.xml";
InputStream inputStream=Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
int row=sqlSession.delete("com.tyut.mapper.StudentsMapper.deleteStudent",8);
if(row!=0){
System.out.println("删除了"+row+"条记录!");
}else{
System.out.println("删除失败");
}
sqlSession.commit();//有提交;
sqlSession.close();
}
}
8、分别进行以下测试,得到测试结果:
(1)按学生id精确查询
(2)模糊查询
(3)按姓名与地址组合查询
(4)添加学生信息
(6)修改(更新)学生信息
(5)删除学生信息