1.在新创建的项目中调用jar包
2.创建实体类bean包,dao包,测试类test包,jdbc.properties,log4j.properties
jdbc.properties文件
properties文件是java中很常用的一种配置文件,文件后缀为“.properties”,属文本文件,文件的内容格式是“键=值”的格式,可以用“#”作为注释,java编程中用到的地方很多,运用配置文件,可以便于java深层次的解耦。例如java应用通过JDBC连接数据库时,通常需要在代码中写数据库连接字符串,下面贴出java通过JDBC连接数据库的代码(以mysql为例):
jdbc.driver=com.mysql.cj.jdbc.Driver //mysql提供的Driver接口的实现类
jdbc.url=jdbc:mysql://user//此处为"jdbc:mysql://localhost:3306/user"的简化形式,user为数据库名
jdbc.user=root
jdbc.password=root
log4j.properties这个文件为日志文件。
log4j.rootLogger=TRACE,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=wocao.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
log4j.logger.mapperNS =TRACE
log4j.logger.com.mybatis=DEBUG
log4j.logger.com.mybatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.mybatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.mybatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.org.springframework=error
log4j.logger.org.apache=ERROR
log4j.logger.org.mybatis=DEBUG
3.在src里面创建mybatis.xml文件,在里面设置数据库连接
<?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>
<!--因为这里调用了jdbc.properties,所以在下面写连接数据库的时候可以直接写
jdbc.properties文件中的起的别名,使用的时候记得加上${}-->
<properties resource="jdbc.properties"/>
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
<typeAliases>
<package name="com.guo.bean"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="jdbc"></transactionManager>
<dataSource type="pooled">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.guo.dao"/>
</mappers>
</configuration>
4.在com.guo.bean中创建实体类Student和ClassInfo
Student类
package com.guo.bean;
public class Student {
private Integer sid;
private String sname;
private String sex;
private String phone;
private String address;
private ClassInfo classInfo;
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public ClassInfo getClassInfo() {
return classInfo;
}
public void setClassInfo(ClassInfo classInfo) {
this.classInfo = classInfo;
}
@Override
public String toString() {
return "Student{" +
"sid=" + sid +
", sname='" + sname + '\'' +
", sex='" + sex + '\'' +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
", classInfo=" + classInfo +
'}';
}
}
ClassInfo类
package com.guo.bean;
public class ClassInfo {
private Integer cid;
private String cname;
private String cinfo;
public Integer getCid() {
return cid;
}
public void setCid(Integer cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getCinfo() {
return cinfo;
}
public void setCinfo(String cinfo) {
this.cinfo = cinfo;
}
@Override
public String toString() {
return "ClassInfo{" +
"cid=" + cid +
", cname='" + cname + '\'' +
", cinfo='" + cinfo + '\'' +
'}';
}
}
5.在com.guo.dao包中创建StudentDao和ClassInfo接口类,在里面创建接口方法
StudentDao接口类并使用注解完成增删查操作
package com.guo.dao;
import com.guo.bean.ClassInfo;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface ClassInfoDao {
@Select("select * from classInfo")
List<ClassInfo> selectAll();//全查
@Select("select * from classInfo where cid=#{cid}")
ClassInfo selectByCid(int cid);//根据id查询信息
@Insert("insert into classInfo (cname,cinfo)values(#{cname},#{cinfo})")
int insert(ClassInfo classInfo);//新增信息
@Delete("delete from classInfo where cid=#{cid}")
int delete(int cid);//根据id删除信息
}
ClassInfo接口类
package com.guo.dao;
import com.guo.bean.Student;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface StudentDao {
//完成学生信息的全查询,要求配置一对一能够查询学生关联的班级信息
@Select("select * from student")
@Results(id = "studentMap",value = {
@Result(id = true, column = "sid", property = "sid"),
@Result(column = "sname",property = "sname"),
@Result(column = "sex",property = "sex"),
@Result(column = "phone",property = "phone"),
@Result(column = "address",property = "address"),
@Result(property = "classInfo",column = "cid",one = @One(select = "com.guo.dao.ClassInfoDao.selectByCid"))
})
List<Student> selectAll();
@Select({"<script>",
"select * from student",
"<where>\n" +
" <if test=\"sname!=null and sname!=''\">\n" +
" or sname like concat('%',#{sname},'%')\n" +
" </if>\n" +
" <if test=\"sex!=null and sex!=''\">\n" +
" or sex like concat('%',#{sex},'%')\n" +
" </if>\n" +
" <if test=\"phone!=null and phone!=''\">\n" +
" or phone like concat('%',#{phone},'%')\n" +
" </if>\n" +
" <if test=\"address!=null and address!=''\">\n" +
" or address like concat('%',#{address},'%')\n" +
" </if>\n" +
" </where>",
"</script>"
})
@ResultMap("studentMap")
List<Student> seach(Student student);
@Update({"<script>",
"update student\n" +
" <set>\n" +
" <if test=\"sname!=null and sname!=''\">\n" +
" sname=#{sname},\n" +
" </if>\n" +
" <if test=\"sex!=null and sex!=''\">\n" +
" sex=#{sex},\n" +
" </if>\n" +
" <if test=\"phone!=null and phone!=''\">\n" +
" phone=#{phone},\n" +
" </if>\n" +
" <if test=\"address!=null and address!=''\">\n" +
" address=#{address},\n" +
" </if>\n" +
" </set>\n" +
" where sid=#{sid}",
"</script>"
})
int update(Student student);
}
6.在com.guo.test包中创建测试类ClassInfoTest和StudentTest中编写测试的方法
ClassInfoTest测试类
package com.guo.test;
import com.guo.bean.ClassInfo;
import com.guo.dao.ClassInfoDao;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TestClassInfo {
InputStream stream=null;
SqlSessionFactoryBuilder builder=null;
SqlSessionFactory factory=null;
SqlSession sqlSession=null;
ClassInfoDao classInfoDao=null;
@Before
public void inic() throws IOException {
stream= Resources.getResourceAsStream("mybatis.xml");
builder=new SqlSessionFactoryBuilder();
factory=builder.build(stream);
sqlSession=factory.openSession();
classInfoDao=sqlSession.getMapper(ClassInfoDao.class);
}
@Test
public void TestselectAll(){
List<ClassInfo> classInfoDaoList = classInfoDao.selectAll();
System.out.println(classInfoDaoList);
}
@Test
public void TestselectByCid(){
ClassInfo classInfo = classInfoDao.selectByCid(1);
System.out.println(classInfo);
}
@Test
public void Testinsert(){
ClassInfo classInfo=new ClassInfo();
classInfo.setCname("111");
classInfo.setCinfo("111");
int i = classInfoDao.insert(classInfo);
if(i>0){
System.out.println("添加成功");
}
}
@Test
public void Testdelete(){
int i = classInfoDao.delete(4);
if (i>0){
System.out.println("删除成功");
}
}
@After
public void di() throws IOException {
sqlSession.commit();
sqlSession.close();
stream.close();
}
}
StudentTest测试类
package com.guo.test;
import com.guo.bean.Student;
import com.guo.dao.ClassInfoDao;
import com.guo.dao.StudentDao;
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.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class TestStudent {
InputStream stream=null;
SqlSessionFactoryBuilder builder=null;
SqlSessionFactory factory=null;
SqlSession sqlSession=null;
StudentDao studentDao=null;
@Before
public void init() throws IOException {
stream= Resources.getResourceAsStream("mybatis.xml");
builder=new SqlSessionFactoryBuilder();
factory=builder.build(stream);
sqlSession=factory.openSession();
studentDao=sqlSession.getMapper(StudentDao.class);
}
@Test
public void TestselectAll(){
List<Student> studentList = studentDao.selectAll();
for (Student student : studentList) {
System.out.println(student);
}
}
@Test
public void Testseach(){
Student student=new Student();
student.setSname("付");
List<Student> studentList = studentDao.seach(student);
for (Student student1 : studentList) {
System.out.println(student1);
}
}
@Test
public void Testupdate(){
Student student=new Student();
student.setSid(5);
student.setSname("ddd");
int i = studentDao.update(student);
if (i>0){
System.out.println("修改成功");
}
}
@After
public void di() throws IOException {
sqlSession.commit();
sqlSession.close();
stream.close();
}
}