1.概述
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC
代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java
的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
2.获取mybatis
maven仓库
3.入门案例
思路:搭建环境—>导入mybatis—>编写代码–>测试
1.创建普通的maven工程
2.在pom.xml文件下引入依赖
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
3.configuration核心配置文件
创建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>
<!--别名-->
<typeAliases>
<package name="com.entiy"></package>
</typeAliases>
<environments default="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/schooldb?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--每一个mapper.xml都需要在核心配置文件中注册 -->
<mappers>
<package name="com.dao"></package>
</mappers>
</configuration>
3.引入实体类
Student:
package com.entiy;
public class Student {
private int StudentID;
private String StudentName;
private String Gender;
private int Age;
public Student() {
}
public Student(int studentID, String studentName, String gender, int age) {
StudentID = studentID;
StudentName = studentName;
Gender = gender;
Age = age;
}
public int getStudentID() {
return StudentID;
}
public void setStudentID(int studentID) {
StudentID = studentID;
}
public String getStudentName() {
return StudentName;
}
public void setStudentName(String studentName) {
StudentName = studentName;
}
public String getGender() {
return Gender;
}
public void setGender(String gender) {
Gender = gender;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
@Override
public String toString() {
return "Student{" +
"StudentID=" + StudentID +
", StudentName='" + StudentName + '\'' +
", Gender='" + Gender + '\'' +
", Age=" + Age +
'}';
}
}
Cesi:
package com.entiy;
import java.io.Serializable;
public class Cesi implements Serializable {
private int id;
private String productname;
private int parent_id;
public Cesi() {
}
public Cesi(int id, String productname, int parent_id) {
this.id = id;
this.productname = productname;
this.parent_id = parent_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname = productname;
}
public int getParent_id() {
return parent_id;
}
public void setParent_id(int parent_id) {
this.parent_id = parent_id;
}
@Override
public String toString() {
return "Cesi{" +
"productname='" + productname + '\'' +
", parent_id=" + parent_id +
'}';
}
}
4.编写持久层StudentDao接口
package com.dao;
import com.entiy.Cesi;
import com.entiy.Student;
import java.util.List;
public interface IstudentDao {
List<Student> selectStudent();
Student selectStudentById(int id);
int insertStudent(Student student);
int updateStudent(Student student);
int deleteStudentByid(int id);
List<Student> selectStudentLike(String likeName);
int insertStudentForId(Cesi cesi);
}
5.编写持久层配置文件StudentDao.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:绑定对应的dao/mapper接口-->
<mapper namespace="com.dao.IstudentDao" >
<!--id对应dao层方法名 resultType:返回值,增删改不写 parameterType参数类型-->
<select id="selectStudent" resultType="com.entiy.Student" parameterType="com.entiy.Student">
select * from studentinfo
</select>
<insert id="insertStudent" parameterType="Student">
insert into studentinfo(StudentID,StudentName,Gender,Age) values(#{StudentID},
#{StudentName},#{Gender},#{Age})
</insert>
<select id="selectStudentById" resultType="Student" parameterType="int">
select * from studentinfo where StudentID=#{id}
</select>
<update id="updateStudent" parameterType="Student" >
update studentinfo set StudentName=#{StudentName},
Gender=#{Gender},Age=#{Age} where StudentID=#{StudentID}
</update>
<delete id="deleteStudentByid" parameterType="int">
delete from studentinfo where studentid=#{id}
</delete>
<select id="selectStudentLike" parameterType="String" resultType="Student">
select * from studentinfo where studentName like #{likeName}
</select>
<!--useGeneratedKeys设置为 true 时,表示如果插入的表id以自增列为主键,则允许 JDBC 支持自动生成主键,并可将自动生成的主键id返回。
useGeneratedKeys参数只针对 insert 语句生效,默认为 false;-->
<insert id="insertStudentForId" parameterType="Cesi" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
insert into product(productname,parent_id) values(#{productname},#{parent_id})
</insert>
</mapper>
6.创建测试类
package com;
import com.dao.IstudentDao;
import com.entiy.Cesi;
import com.entiy.Student;
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.InputStream;
import java.util.List;
public class myBatisTest {
public static void main(String[] args) {
try{
//1.读取配置文件
InputStream inputStream= Resources.getResourceAsStream("myBatisconfig.xml");
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory=builder.build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
IstudentDao mapper = sqlSession.getMapper(IstudentDao.class);
//查询
/* List<Student> students = mapper.selectStudent();
for (Student s:students) {
System.out.println(s);
}*/
//新增
/* Student student=new Student();
student.setStudentID(000);
student.setStudentName("sss");
student.setAge(20);
student.setGender("男");
int i = mapper.insertStudent(student);
System.out.println(i);
sqlSession.commit();*/
//根据id获取对象
/* Student student = mapper.selectStudentById(44);
System.out.println(student);*/
//修改
/* Student student=new Student();
student.setAge(200);
student.setStudentName("df");
student.setStudentID(44);
student.setGender("女");
int i = mapper.updateStudent(student);
System.out.println(i);
sqlSession.commit();*/
//删除
/*int i = mapper.deleteStudentByid(0);
System.out.println(i);
sqlSession.commit();*/
//模糊查询
/* List<Student> students = mapper.selectStudentLike("%马%");
System.out.println(students);*/
//获取自增id
Cesi cesi=new Cesi();
cesi.setProductname("aaa");
cesi.setParent_id(9);
int i = mapper.insertStudentForId(cesi);
System.out.println(cesi.getId());
sqlSession.commit();
}catch (Exception e){
e.printStackTrace();
}
}}
7.配置mybatis的日志,在resouces目录下创建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=mybatis.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