MyBatis简明教程-手把手教你配环境-maven+idea
MyBatis中文官方文档
什么是 MyBatis?
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
1.项目结构,该项目为一个简单的web项目,使用maven构建,关于如何使用maven创建项目,请自行百度
2.Student为对应数据库的实体类
package entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
/** * */
private Integer id;
/** * */
private String name;
/** * */
private String sex;
/** * */
private String specialty;
/** * */
private String grade;
public Student(String name, String sex, String specialty, String grade) {
this.name = name;
this.sex = sex;
this.specialty = specialty;
this.grade = grade;
}
}
3.创建mybatis-config.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>
<settings>
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
<setting name="cacheEnabled" value="false"/>
<!-- Sets the number of seconds the driver will wait for a response from the database -->
<setting name="defaultStatementTimeout" value="5"/>
<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- Allows JDBC support for generated keys. A compatible driver is required. This setting forces generated keys to be used if set to true, as some drivers deny compatibility but still work -->
<setting name="useGeneratedKeys" value="true"/>
</settings>
<!-- Continue editing here -->
<!-- 数据库环境 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/stumanage?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 映射文件 -->
<mappers>
<mapper resource="StudentMapper.xml"/>
</mappers>
</configuration>
4.创建sql语句接口以及对应的mapper.xml文件
package dao;
import entity.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface StudentMapper {
int insert(@Param("student") Student student);
int insertSelective(@Param("student") Student student);
int insertList(@Param("students") List<Student> students);
int updateByPrimaryKeySelective(@Param("student") Student student);
void delete(Integer integer);
Student getStudentById(Integer integer);
void update(Student student);
Student selectAll();
}
<?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="dao.StudentMapper">
<!--auto generated Code-->
<resultMap id="BaseResultMap" type="entity.Student">
<result column="id" property="id" jdbcType="INTEGER"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="sex" property="sex" jdbcType="VARCHAR"/>
<result column="specialty" property="specialty" jdbcType="VARCHAR"/>
<result column="grade" property="grade" jdbcType="VARCHAR"/>
</resultMap>
<!--auto generated Code-->
<sql id="Base_Column_List">
id,
`name`,
sex,
specialty,
grade
</sql>
<!--auto generated Code-->
<insert id="insert" parameterType="entity.Student">
INSERT INTO student (
name,
sex,
specialty,
grade
) VALUES (
#{name},
#{sex},
#{specialty},
#{grade}
)
</insert>
<delete id="delete" parameterType="int">
delete from student
where id = #{id}
</delete>
<update id="update" parameterType="entity.Student">
update student
set name = #{name}, sex = #{sex}, specialty = #{specialty}, grade = #{grade}
where id = #{id}
</update>
<select id="getStudentById" parameterType="int" resultType="entity.Student">
select *
from student
where id = #{id}
</select>
<!--若查询的返回结果是集合 则resultType类型应为具体类型 而不是list-->
<select id="selectAll" resultType="entity.Student">
select *
from student
</select>
<!--auto generated Code-->
<insert id="insertSelective" useGeneratedKeys="true" keyProperty="student.id">
INSERT INTO student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="student.id!=null">id,</if>
<if test="student.name!=null">`name`,</if>
<if test="student.sex!=null">sex,</if>
<if test="student.specialty!=null">specialty,</if>
<if test="student.grade!=null">grade,</if>
</trim>
VALUES
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="student.id!=null">#{student.id,jdbcType=INTEGER},
</if>
<if test="student.name!=null">#{student.name,jdbcType=VARCHAR},
</if>
<if test="student.sex!=null">#{student.sex,jdbcType=VARCHAR},
</if>
<if test="student.specialty!=null">#{student.specialty,jdbcType=VARCHAR},
</if>
<if test="student.grade!=null">#{student.grade,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<!--auto generated Code-->
<insert id="insertList">
INSERT INTO student (
id,
`name`,
sex,
specialty,
grade
)VALUES
<foreach collection="students" item="student" index="index" separator=",">
(
#{student.id,jdbcType=INTEGER},
#{student.name,jdbcType=VARCHAR},
#{student.sex,jdbcType=VARCHAR},
#{student.specialty,jdbcType=VARCHAR},
#{student.grade,jdbcType=VARCHAR}
)
</foreach>
</insert>
<!--auto generated Code-->
<update id="updateByPrimaryKeySelective">
UPDATE student
<set>
<if test="student.name != null">`name`= #{student.name,jdbcType=VARCHAR},</if>
<if test="student.sex != null">sex= #{student.sex,jdbcType=VARCHAR},</if>
<if test="student.specialty != null">specialty= #{student.specialty,jdbcType=VARCHAR},</if>
<if test="student.grade != null">grade= #{student.grade,jdbcType=VARCHAR}</if>
</set>
WHERE id = #{student.id,jdbcType=INTEGER}
</update>
</mapper>
5.测试类-增删查改
import entity.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 org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/** * @ClassName: Main * @Author: Leo * @Description: * @Date: 2019/4/8 21:13 */
public class Main {
private static Logger logger = LogManager.getLogger("Leo");
public static void main(String[] args) {
SqlSessionFactory sqlSessionFactory;
SqlSession sqlSession;
//配置文件路径
String resources = "mybatis-config.xml";
InputStream inputStream = null;
try {
//加载配置文件
inputStream = Resources.getResourceAsStream(resources);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSession = sqlSessionFactory.openSession();
//插入一条记录
Student student = new Student("小明", "男", "数学", "大一");
int insert = sqlSession.insert("insert", student);
logger.debug("插入一条记录: " + insert);
//根据学号查询记录
Student student1 = sqlSession.selectOne("getStudentById", 1);
logger.debug("根据学号查询: " + student1.toString());
//查询所有记录
List<Student> list = sqlSession.selectList("selectAll");
for (Student student2 : list) {
logger.debug("查询所有记录: " + student2.toString());
}
//更新一条记录
Student student3 = new Student(1, "更新名字", "无", "人工智能", "大五");
sqlSession.update("update", student3);
//删除一条记录
int delete = sqlSession.delete("delete", 2);
logger.debug("删除一条记录: " + delete);
sqlSession.commit();
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}