核心配置文件
替换连接信息,解决硬编码问题 文件名:mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<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/edu_mybatis?useSSL=false&serverTimezone=Asia/Shanghai&useTimezone=true"/>
<property name="username" value="root"/>
<property name="password" value="mmforu"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--配置相应的实体接口映射文件 resource属性里是文件的路径-->
<mapper resource="UserMapper.xml"/>
</mappers></configuration>
编写sql映射文件
统一管理sql语句,解决硬编码问题 文件名: UserMapper .xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 属性 namespace:名称空间 建议:写相应实体接口的全名 -->
<mapper namespace="test">
<select id="findAll" resultType="com.shuilidianli.pojo.User">
select * from tb_user;
</select>
</mapper>
编写代码
① 根据数据库表,定义pojo类
② 加载核心配置文件,获取SqlSessionFactory对象
③ 获取SqlSession对象,执行sql语句
④ 释放资源
public static void main(String[] args) throws IOException {
// 1. 加载mybatis的核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);//2. 获取SqlSession对象,用他来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();//3. 执行sql 调用selectList方法,传参 namespace.id,来指定要执行的sql语句
List<User> users = sqlSession.selectList("test.findAll");
System.out.println(users);//4. 释放资源
sqlSession.close();
}
Mapper代理开发
解决原生方式中的硬编码,简化后期执行的SQL
原生写法:
List<User> users = sqlSession.selectList("test.findAll")
代理写法:
UsermMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> users = mapper.findAll();
细节:如果Mapper接口名称与SQL映射文件名称相同,并且在同一个目录下,则可以使用包扫描的方式简化sql映射文件的加载
<mappers>
<mapper resource=/>
<package namne="com.sldl.mapper"/>
</mappers>
映射
定义java实体类时,有自己的命名规范, 比如属性名不建议使用下划线, 多个单词时,使用驼峰命名法 定义表时,表的字段有自己的命名规范, 列名是不区分大小写的,多个单词使用下划线连接。 有的时候: 字段名称和属性名称,如果相同,可以自动映射成功,进行赋值, 即字段的值赋值给属性。 但是有的时候,名称不一致,则不能自动映射成功。此时,我们可以自己定义映射关系。 resutlMap: 用于自定义映射关系的 id: 这个映射关系的唯一标识 type: 用于指定具体的实体类型 小贴士: 如果不想编写映射关系, 书写sql语句时,可以使用列别名,列别名必须和实体类的属性名相同
<resultMap id="employeeMap" type="employee"> <!-- id子标签,专门用于主键映射 culumn属性: 用于指定表的列名 property属性:用于指定实体类的属性名 List<Employee> findAll(): 方法返回的是集合类型, resultType书写集合的元素类型即可。 --> <id column="empno" property="id"></id> <result column="ename" property="ename"></result> <result column="job" property="job"></result> <result column="mgr" property="mgr"></result> <result column="hiredate" property="hiredate"></result> <result column="sal" property="sal"></result> <result column="comm" property="bonus"></result> <result column="deptno" property="deptno"></result> </resultMap>
#{}与${}
#{}: 在底层转义时,会被翻译成?形式。 与PreparedStatement的用法一样。传值时,?会被值所代替。 字符串形式的实际参数,在传递过来后,会自动带上单引号。 而且没有SQL注入风险。
${}: 就是一个普通的拼接。 如果需要单引号,需要自己拼接, 有SQL注入风险。例如:
select * from emp where ename = '${asdfkjaskdfj}'
parameterType
parameterType: 用于指定参数的类型, 可以书写别名: Integer类型的别名: int integer int类型的别名: _int _integer Int Map类型的别名: map HashMap : hashmap List : list ArrayList : arraylist Object : object String : string
接口里的方法带有参数,在此处就应该指定parameterType : 如果参数是实体类, 那么站位符的名字必须和实体类的属性名相同
<!-- void addEmployee(Employee e); 接口里的方法带有参数,在此处就应该指定parameterType : 如果参数是实体类, 那么站位符的名字必须和实体类的属性名相同 --> <insert id="addEmployee" parameterType="employee"> insert into emp values (null,#{ename},#{job},#{mgr},#{hiredate},#{sal},#{bonus},#{deptno}) </insert>
mapper与select子标记
Sql映射文件: mapper是根标记,只能有一个, namespace: 命名空间,相当于mapper的唯一标识符,不能重名 该文件里书写的内容,就是与数据库进行交互的SQL语句对应的配置 比如 select, insert, delete,update等 注意: 如果使用Mapper代理方式,namespace必须使用接口的全限定名
<mapper namespace="com.mybatis.mapper.StudentMapper">
select子标记: 用于书写select的SQL语句 属性ID: select子标记的唯一标识符,也是对应的接口里的方法名称 属性ResutlType: 结果类型, 可以是java中的任何类型。 实体类,基本类型,引用类型(Map)
<select id="findAll" resultType="student"> select * from student </select> <!-- Student findById(int id); --> <select id="findById" resultType="student"> select * from student where id=#{abc} </select>
mybatis-config.xml的说明
mybatis的核心配置文件
核心配置文件中的子标签,必须按照以下的顺序进行配置,否则报错 properties?,settings?,typeAliases?,typeHandlers?,objectFactory?, objectWrapperFactory?,reflectorFactory?,plugins?, environments?,databaseIdProvider?,mappers?
typeAliases
<typeAlias type="com.mybatis.pojo.StudentCard" <typeAlias type="com.mybatis.pojo.Student" alias="Student" 使用扫描包的方式,来给实体类起别名,默认自己的类名,也不区分大小写
environments: 用来配置各种数据源 deufalt: 用于指定使用哪一个数据源, 通过书写environment子标记的id(唯一标识符)来确定
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- mybatis的核心配置文件
核心配置文件中的子标签,必须按照以下的顺序进行配置,否则报错
properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,
objectWrapperFactory?,reflectorFactory?,plugins?,
environments?,databaseIdProvider?,mappers?
-->
<configuration>
<!-- 引入properties形式的文件: resource属性用于指定文件的路径 -->
<properties resource="jdbc.properties"/>
<!-- 开启mybatis的日志组件功能 ,可以打印sql语句 -->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 用于给实体类起别名的, type:具体的实体类名称,
alias: 别名 不区分大小写 可以不写,如果不写则使用类名作为别名
-->
<typeAliases>
<!-- <typeAlias type="com.mybatis.pojo.StudentCard"/>-->
<!-- <typeAlias type="com.mybatis.pojo.Student" alias="Student"/>-->
<!-- 使用扫描包的方式,来给实体类起别名,默认自己的类名,也不区分大小写 -->
<package name="com.mybatis.pojo"/>
</typeAliases>
<!-- environments: 用来配置各种数据源
deufalt: 用于指定使用哪一个数据源, 通过书写environment子标记的id(唯一标识符)来确定
-->
<environments default="mysql">
<!--environment: 用于指定数据源的配置信息:
属性Id: 数据源的唯一标识符-->
<environment id="mysql">
<!-- 指定mybatis的事务处理方式: JDBC|MANAGED
JDBC: Mybatis使用JDBC的原生事务处理方法,即使用JDBC的commit()、rollback()方法进行手动调用
MANAGED: mybatis自己不处理事务,交给其他容器来管理mybatis的事务
-->
<transactionManager type="JDBC"/>
<!-- type: 数据源的类型,有三个值: POOLED|UNPOOLED|JNDI
POOLED: 使用连接池技术, Connection对象从连接池中获取, 不用的时候归还给连接池。
UNPOOLED: 不使用连接池。
JNDI: 已经过时了。-->
<dataSource type="POOLED">
<!-- 数据源的driver属性: value:引入properties文件里的value值 -->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
<environment id="oracle">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 数据源的driver属性: value:引入properties文件里的value值 -->
<property name="driver" value="oracle"/>
<property name="url" value="oracle"/>
<property name="username" value="oracle"/>
<property name="password" value="oracle"/>
</dataSource>
</environment>
</environments>
<!-- 用于指定所有的Sql映射文件 : 注册Sql映射文件 -->
<mappers>
<!-- mapper: 用于指定一个具体的SQL映射文件, resource属性用于指定该文件的路径
如果是多层路径,必须使用斜杠隔开 ,相对的是resources文件夹
-->
<!-- <mapper resource="com/mybatis/mapper/StudentMapper.xml"/>-->
<!-- <mapper resource="com/mybatis/mapper/StudentCardMapper.xml"/>-->
<!-- 如果mapper的映射配置越来越多,我们可以使用扫描包的功能来配置 -->
<package name="com.mybatis.mapper"/>
</mappers>
</configuration>