一、创建项目(联网)
1、创建Maven项目
2、配置本地Maven(使用自己电脑Maven路径)
3、配置Java源文件
4、配置文件
(1)pom.xml(添加源文件没有的部分)
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- 日志文件管理包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.6</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
</dependencies>
(2)log4j.properties
### 日志等级 ###
log4j.rootLogger = INFO,D
### 输出控制台 ###
log4j.logger.toConsole=debug,stdout
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n
### 输出日志文件 ###
## 其中File 可以采用绝对路径 亦可以采用相对路径 catalina.home 是tomcat目录 如果没有logs文件夹 将会报错 ##
## 更加倾向于将日志文件放在 D:/database/log4j/log4jTest/logtest.log ##
log4j.logger.daily=INFO,D
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = D:/database/log4j/log4jTest/logtest.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n
##log4j.logger.org.apache.ibatis=debug,stdout
##log4j.logger.java.sql=debug,stdout
二、MyBatis的简单应用
1、数据准备(MySQL)
(1)创库、建表
drop database if exists chapter01;
create database chapter01;
use chapter01;
create table student(
sid int primary key auto_increment,
sname varchar(20),
age varchar(20),
course varchar(20)
);
(2)插入数据
insert into student(sname,age,course) values('ZhangSan','20','Java');
insert into student(sname,age,course) values('Lisi','21','Java');
insert into student(sname,age,course) values('WangWu','22','Java');
insert into student(sname,age,course) values('ZhaoLiu','22','Python');
insert into student(sname,age,course) values('SunQi','22','PHP');
insert into student(sname,age,course) values('ZhangSanSan','22','PHP');
2、创建POJO类
package com.qf.chapter01.pojo;
public class Student {
private int sid;
private String sname;
private String age;
private String course;
public Student() {
super();
}
public Student(int sid, String sname, String age, String course) {
super();
this.sid = sid;
this.sname = sname;
this.age = age;
this.course = course;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + ", " + "age=" + age + ", " + "course=" + course + "]";
}
}
3、mybatis-config.xml(resources目录下新建)
<?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">
<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/chapter01" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<!-- 配置映射文件的位置 -->
<mappers>
<mapper resource="chapter01/StudentMapper.xml" />
</mappers>
</configuration>
4、StudentMapper.xml
resources目录下新建chapter01目录,chapter01目录新建StudentMapper.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">
<mapper namespace="student">
<select id="findStudentBySid" parameterType="Integer"
resultType="com.qf.chapter01.pojo.Student">
select * from Student where sid=#{sid}
</select>
<select id="findStudentBySname" parameterType="String"
resultType="com.qf.chapter01.pojo.Student">
select * from student where sname like '%${value}%'
</select>
<insert id="addStudent" parameterType="com.qf.chapter01.pojo.Student">
insert into student(sname,age,course) values(#{sname},#{age},#{course})
</insert>
<update id="updateStudent"
parameterType="com.qf.chapter01.pojo.Student">
update student set sname=#{sname},course=#{course} where sid=#{sid}
</update>
<delete id="deleteStudent" parameterType="Integer">
delete from student where sid=#{sid}
</delete>
</mapper>
5、测试类
(1)通过sid查询学生信息
package com.qf.chapter01.test;
import java.io.*;
import com.qf.chapter01.pojo.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
public class TestFindBySid {
public static void main(String[] args) {
// 读取配置文件
String resource = "mybatis-config.xml";
try {
InputStream in = Resources.getResourceAsStream(resource);
// 创建SQLSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession对象
SqlSession sqlSession = factory.openSession();
// 调用SqlSession对象的selectOne()方法执行查询
Student student = sqlSession.selectOne("student.findStudentBySid", 1);
System.out.println(student.toString());
// 关闭SqlSession
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
(2)通过sname模糊查询学生信息
package com.qf.chapter01.test;
import java.io.*;
import java.util.List;
import com.qf.chapter01.pojo.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
public class TestFindBySname {
public static void main(String[] args) {
// 读取配置文件
String resource = "mybatis-config.xml";
try {
InputStream in = Resources.getResourceAsStream(resource);
// 创建SQLSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession对象
SqlSession sqlSession = factory.openSession();
// 调用SqlSession的selectList()方法执行查询
List<Student> selectList = sqlSession.selectList("student.findStudentBySname", "ZhangSan");
for (Student student : selectList) {
System.out.println(student.toString());
}
// 关闭SqlSession
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
(3)添加学生信息
package com.qf.chapter01.test;
import java.io.*;
import com.qf.chapter01.pojo.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
public class TestAdd {
public static void main(String[] args) {
// 读取配置文件
String resource = "mybatis-config.xml";
try {
InputStream in = Resources.getResourceAsStream(resource);
// 创建SQLSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession对象
SqlSession sqlSession = factory.openSession();
Student student = new Student();
student.setSname("ZhouBa");
student.setAge("21");
student.setCourse("Java");
// 调用SqlSession对象的insert()方法执行插入
int result = sqlSession.insert("student.addStudent", student);
if (result > 0) {
System.out.println("成功插入" + result + "条数据");
} else {
System.out.println("插入操作失败");
}
// 提交事务
sqlSession.commit();
// 关闭SqlSession
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
(4)更新学生信息
package com.qf.chapter01.test;
import java.io.*;
import com.qf.chapter01.pojo.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
public class TestUpdate {
public static void main(String[] args) {
// 读取配置文件
String resource = "mybatis-config.xml";
try {
InputStream in = Resources.getResourceAsStream(resource);
// 创建SQLSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession对象
SqlSession sqlSession = factory.openSession();
Student student = new Student();
student.setSid(7);
student.setSname("WuJiu");
student.setCourse("Python");
// 调用SqlSession对象的update()方法执行更新
int result = sqlSession.update("student.updateStudent", student);
if (result > 0) {
System.out.println("成功更新" + result + "条数据");
} else {
System.out.println("更新操作失败");
}
// 提交事务
sqlSession.commit();
// 关闭SqlSession
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
(5)删除学生信息
package com.qf.chapter01.test;
import java.io.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;
public class TestDelete {
public static void main(String[] args) {
// 读取配置文件
String resource = "mybatis-config.xml";
try {
InputStream in = Resources.getResourceAsStream(resource);
// 创建SQLSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession对象
SqlSession sqlSession = factory.openSession();
// 调用SqlSession对象的delete()方法执行删除
int result = sqlSession.delete("student.deleteStudent", 7);
if (result > 0) {
System.out.println("成功删除" + result + "条数据");
} else {
System.out.println("删除操作失败");
}
// 提交事务
sqlSession.commit();
// 关闭SqlSession
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}