Mybatis官网
Mybatis是一款优秀的持久层框架,它支持定制化SQL,存储过程以及高级映射。mybaits 避免了几乎所有的JDBC代码和手动设置参数以及获取结果集 。
Mybatis可以使用简单的xml或注解来配置和映射原生信息,将接口和java的POJO(Plain Old java Objects,普通java对象)映射成数据库中的记录。
Mybatis是基于JDBC做的简单的映射包装。
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.30version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
配置数据源,事务,加载映射文件。 后文详解
/**
* 创建Pojo类,和数据库表Student对应
* 属性需要与数据库一一对应
*/
public class Student {
private int SID;
private String Sname;
private String Ssex;
private int Sage;
省略get和set方法
}
该接口中的方法名需要唯一,每一个接口方法均与Mapper.xml文件sql语句一一映射
public interface StudentMapper {
// 需求:通过ID查询Student表中用户信息
//select * from Student where SID = XXX
public Student getStudentById(int sid);
}
<mapper namespace="com.dao.StudentMapper">
<select id="getStudentById" parameterType="java.lang.Integer" resultType="com.bean7.Student">
select * from Student where SID = #{sid}
select>
mapper>
<mappers>
<mapper resource="mapper/StudentMapper.xml"/>
mappers>
/**
* @Created with IntelliJ IDEA
* @Description:
* @Package: PACKAGE_NAME
* @author: FLy-Fly-Zhang
* @Date: 2019/7/26
* @Time: 13:56
*/
public class App {
public static void main(String[] args) throws IOException {
String resource="mybatis-config.xml";
//读取配置文件
InputStream inputStream=Resources.getResourceAsStream(resource);
//创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
//设置是主动提交事务还是手动,默认手动
sqlSessionFactory.openSession(true);
//得到sqlSession
SqlSession sqlSession=sqlSessionFactory.openSession();
//通过动态代理产生StrudentMapper对象
StudentMapper mapper=sqlSession.getMapper(StudentMapper.class);
//调用对应接口方法,进行sql语句操作
Student student = mapper.getStudentById(1);
//若未设置主动提交事务,进行手动提交
sqlSession.commit();
System.out.println(student);
}
}
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mybatis
db.username=root
db.password=12345678
<properties>-->
<property name="db.properties" value="db.properties"/>
properties>
<settings>
settings>
<typeAliases>
<typeAlias type="com.bean7.Student" alias="student"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
dataSource>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="xxxx"/>
<property name="password" value="xxxxx"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="mapper7/StudentMapper.xml"/>
mappers>
mybatis中有两个常见的符号#和KaTeX parse error: Expected 'EOF', got '#' at position 25: …的时候是很常见的,我的理解就是#̲是需要进行预编译的,是字符串进…是直接进行字符串的替换工作,两者各有有缺点。
通过#{ }可以实现preparedStatement向占位符中设置值,
自动进行java类型和jdbc类型转换,
#{ }可以有效防止sql注入。
#{ }可以接收简单类型值或pojo属性值。
如果parameterType传输单个简单类型值,#{ }括号中可以是value或其它名称。
我们一般在刚刚接触到mybatis的时候都是使用的是#{变量名字},来进行sql语句的赋值工作,比如 select * from table_name where name = #{name},来进行查询,在接口里面传入Map或者是String都是可以的,这样的是mybatis进行了语句的编译工作,#{name},必须要放到name=后面,这样才会编译通过,进行执行sql语句。
${ }可以将parameterType 传入的内容拼接在sql中
不进行jdbc类型转换,
$ { }可以接收简单类型值或pojo属性值,
如果parameterType传输单个简单类型值,${ }括号中只能是value。
我们需要进行变化传输sql语句,这个时候一般都会用到的是等mybatis里面的动态标签来动态拼接sql语句,但是有的时候根据一些业务场景是需要传输表名或者是特定的变量名的,这个时候就需要根据业务来动态的改变查询的表名等问题,这个时候 的 好 处 就 体 现 了 , 的好处就体现了, 的好处就体现了,我的感觉就是单纯的字符串替换,比如,select * from table_name where name = ${name}这个时候mybatis不需要编译而是直接进行字符串的替换工作,比如我要传入一个表名,select * from KaTeX parse error: Expected 'EOF', got '#' at position 26: …} where name = #̲{name},这个时候在前台就…{tableName}就是单纯的字符串替换,而#{name}则需要进行编译才可以赋值
<mapper namespace="com.dao7.StudentMapper">
<resultMap id="resultStudent" type="com.bean7.Student">
<id column="SID" property="SID" javaType="java.lang.Integer" jdbcType="INTEGER">id>
<result column="Sname" property="name">result>
<result column="Ssex" property="Ssex">result>
<result column="Sage" property="Sage">result>
resultMap>
<select id="getStudentById" parameterType="java.lang.Integer" resultMap="resultStudent">
select * from Student where SID = #{sid}
select>
insert into Student (SID,Sname) values (#{SID},#{Sname})
insert>
<delete id=""/>
<update id=""/>
public interface StudentMapper {
/**
* 通过对象新增
* @param student
* @return
*/
@Insert("insert into student(student_number, student_name, age) values (#{studentNumber, jdbcType=VARCHAR}, #{studentName, jdbcType=VARCHAR}, #{age, jdbcType=INTEGER})")
int insertByObject(Student student);
/**
* 通过map新增
* @param map
* @return
*/
@Insert("insert into student(student_number, student_name, age) values (#{studentNumber, jdbcType=VARCHAR}, #{studentName, jdbcType=VARCHAR}, #{age, jdbcType=INTEGER})")
int insertByMap(Map<String, Object> map);
/**
* 通过编号查询
* @param studentNumber
* @return
*/
@Select("select * from student where student_number = #{studentNumber}")
@Results({
@Result(column = "student_number", property = "studentNumber"),
@Result(column = "student_name", property = "studentName"),
@Result(column = "age", property = "age")
})
Student findByStudentNumber(String studentNumber);
/**
* 通过姓名查询
* @param studentName
* @return
*/
@Select("select * from student where student_name = #{studentName}")
@Results({
@Result(column = "student_number", property = "studentNumber"),
@Result(column = "student_name", property = "studentName"),
@Result(column = "age", property = "age")
})
List<Student> findByStudentName(String studentName);
/**
* 通过编码删除
* @param studentNumber
* @return
*/
@Delete("delete from student where student_number = #{studentNumber}")
int deleteByStudentNumber(String studentNumber);
/**
* 通过对象修改
* @param student
* @return
*/
@Update("update student set student_name = #{studentName}, age = #{age} where student_number = #{studentNumber}")
int updateByObject(Student student);
/**
* 通过编码修改名字
* 传多个参数时必须使用@Param("")
* @param studentName
* @param StudentNumber
* @return
*/
@Update("update student set student_name = #{studentName} where student_number = #{studentNumber}")
int updateStudentNameByStudentNumber(@Param("studentName") String studentName, @Param("studentNumber") String StudentNumber);
}
Mybatis全面详解
Mybatis教程