学习框架思路:配置环境-->导入-->编写代码-->测试。
增删改必须要提交事务SqlSession.commit().
创建数据库user类
创建maven项目,domain中实体类对应数据库user
创建userdao接口
List<UserInfo> findAll();
创建userMapper.xml(类似于userdao的实现类)
<?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="com.xx.dao.UserDao"> <select id="findAll" resultType="com.xx.domain.UserInfo"> select * from user </select> </mapper>
在resources中创建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> <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/ssm"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/xx/mapper/userMapper.xml"/> </mappers> </configuration>
创建MybatisUtils
private static SqlSessionFactory factory; static { try { String resources = "mybatis-config.xml"; InputStream in = Resources.getResourceAsStream(resources); factory = new SqlSessionFactoryBuilder().build(in); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return factory.openSession(); }
7.测试
private UserDao user; private SqlSession sqlSession; @Before public void setUp() throws Exception { sqlSession = MybatisUtils.getSqlSession(); user = sqlSession.getMapper(UserDao.class); } @After public void tearDown() throws Exception { sqlSession.close(); } @Test public void findAll() { List<UserInfo> list = user.findAll(); for (UserInfo info : list) { System.out.println(info); } }
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
假设实体类,或者数据库中的表,字段或者参数过多,应当考虑使用Map!
int addUser2(Map<String,Object> map);
<insert id="addUser2" parameterType="map"> insert into user(id,username) values (#{id},#{username}); </insert>
@Test public void addUser2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); HashMap<String, Object> map = new HashMap<>(); map.put("id",1); map.put("username","钟离"); int i = mapper.addUser2(map); if (i>0){ System.out.println("插入成功"); } sqlSession.commit(); sqlSession.close(); }
Map传递参数,直接在sql中取出key即可![ parameterType="map" ]
对象传递参数,直接在sql中取出对象即可![ parameterType="Object" ]
只有一个基本数据类型的情况下,可以直接在sql中取到!
多个参数用Map或者注解!
sql注入:
添加额外条件
select * from user where id = ? select * from user where id = 1 or 1=1
事务管理器(transactionManager) type="[JDBC|MANAGED]"
数据源(dataSource)type="[UNPOOLED|POOLED|JNDI]"
mybatis默认的事务管理器是JDBC,连接池:POOLED
<properties resource="druid.properties"> <property name="username" value="root"/> <property name="password" value="123456"/> </properties>
可以直接引入外部文件
可以在其中增加一些属性配置
如果两个文件有同一个字段,外部会覆盖内部的赋值
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写
<typeAliases> <typeAlias alias="User" type="com.xx.domain.User"/> </typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
实体类比较多的话可以用这种
<typeAliases> <package name="com.xx.domain"/> </typeAliases>
在实体类上面添加注解
@Alias("user") public class User { ... }
方式一:(推荐)
<!-- 使用相对于类路径的资源引用 --> <mappers> <mapper resource="com/xx/mapper/userMapper.xml"/> </mappers>
方式二:
<!-- 将包内的映射器接口实现全部注册为映射器 --> <mappers> <package name="com.xx.mapper"/> </mappers>
接口和他的Mapper配置文件同名(推荐)
接口和他的Mapper配置文件放在同一个包下(推荐)
<resultMap id="UserMap" type="user"> <!-- column 数据库中的字段,property实体类中的属性 --> <!-- <result column="id" property="id" /> --> <result column="username" property="name"/> <result column="password" property="pwd" /> </resultMap> <select id="findUserById" resultMap="UserMap" > select * from user where id=#{id} </select>
<settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings>
方式一
接口
//分页查询 List<UserInfo> findUserByLimit(Map<String,Integer> map);
实现xml
<select id="findUserByLimit" parameterType="map" resultType="user"> select * from user limit #{startIndex},#{pageSize} </select>
测试
@Test public void findUserByLimit(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); Map<String, Integer> map = new HashMap<String, Integer>(); map.put("startIndex",0); map.put("pageSize",2); List<UserInfo> userList = mapper.findUserByLimit(map); for (UserInfo userInfo : userList) { System.out.println(userInfo); } sqlSession.close(); }
方式二
RowBounds分页
接口
//分页2 List<User> getUserByRowBounds();
Mapper.xml
<!-- 分页2-->
测试
@Test public void getUserByRowBounds(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); //RowBounds实现 RowBounds rowBounds = new RowBounds(0, 2); //通过java代码层面实现分页 List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds); for (User user : userList) { System.out.println(user); } sqlSession.close();
}
方式三(插件)
根本原因:解耦,可拓展、提高复用、分层开发中不用管具体的实现,大家都遵守共同的标准,使开发变得更容易,规范性更好。
本质:反射机制实现 底层:动态代理!
@Data public class Student { private int id; private String name; private Teacher teacher; }
<select id="findAll" resultMap="StudentTeacher"> select * from student </select> <resultMap id="StudentTeacher" type="Student"> <result property="id" column="id"/> <result property="name" column="name"/> <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap> <select id="getTeacher" resultType="Teacher"> select * from teacher where id=#{id} </select>
<select id="findAll2" resultMap="StudentTeacher2"> select s.id sid, s.name sname, t.name tname from student s,teacher t where t.`id`=s.`tid`; </select> <resultMap id="StudentTeacher2" type="student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="teacher"> <result property="name" column="tname"/> </association> </resultMap>
@Data public class Teacher { private int id; private String name; private List<Student> students; }
<select id="findTeacher" resultMap="TeacherStudent"> select t.`id` tid,t.`name` tname,s.`id` sid,s.`name` sname from student s,teacher t where t.`id`=s.`tid` </select> <resultMap id="TeacherStudent" type="teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <collection property="students" ofType="student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="tid"/> </collection> </resultMap>
思路总结:先写查询语句,然后结果集映射,teacher类里有三个属性,前两个属性与数据库属性对应,第三个属性是集合要用collection,集合属性是students,类型(ofType)是student,然后对student里的属性与数据库对应。
关联-association【多对一】
集合-collection【一对多】
javaType & ofType
javaType 用来指定实体类中属性的类型
ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!
注意:
保证SQL的可读性,尽量保证通俗易懂
注意一对多和多对一中,属性名和字段的问题!
如果问题不好排查错误,可以使用日志,建议使用Log4j
面试高频:
Mysql引擎
InnoDB底层原理
索引
索引优化
//模糊查询 List<Blog> queryBlog(Map map);
<select id="queryBlog" parameterType="map" resultType="blog"> select * from blog where 1=1 <if test="title != null"> and title=#{title} </if> <if test="author != null"> and author=#{author} </if> </select>
@Test public void queryBlog() { SqlSession sqlSession = MybatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap<String, Object> map = new HashMap<>(); map.put("title","Spring"); mapper.queryBlog(map); sqlSession.close(); }
只能执行一个,尽量包裹在where里面
<select id="queryBlogChoose" parameterType="map" resultType="blog"> select * from blog <where> <choose> <when test="title!=null"> title=#{title} </when> <when test="author!=null"> author=#{author} </when> <otherwise> views=#{views} </otherwise> </choose> </where> </select>
where 会智能补全或者删除and/or
set会智能添加或者删除后面的逗号
动态SQL本质还是SQL语句,只是可以在SQL层面,去执行一个逻辑代码。
<select id="queryBlogForeach" parameterType="map" resultType="blog"> select * from blog <where> <foreach collection="ids" item="id" open=" ( " close=" ) " separator=" or "> id = #{id} </foreach> </where> </select>
把公共部分抽取出来,类似于方法
<sql id="if-title-author"> <if test="title != null"> and title=#{title} </if> <if test="author != null"> and author=#{author} </if> </sql> <select id="queryBlog" parameterType="map" resultType="blog"> select * from blog <where> <include refid="if-title-author"></include> </where> </select>
动态sql就是在拼接sql语句,只需要保证sql的正确性,按照sql的格式,去排列组合。
延迟加载:多表联查时,用到啥了去查询啥,没用到就推迟加载,按需查询。适合多对一和一对一,例如账户和用户。
缓存是为了提高查询效率
什么是缓存[Cache]?
存在内存中的临时数据。
将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库查询文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
为什么使用缓存?
减少和数据库的交互次数,减少系统开销,提高系统效率。
什么样的数据能使用缓存?
经常查询并且不经常改变的数据。【可以使用缓存】
Mybatis缓存
Mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的
提升查询效率。
Mybatis系统中默认定义了两级缓存:一级缓存和二级缓存
默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也称为本地缓存)
二级缓存需要手动开启和配置,它是基于namespace级别的缓存。
为了提高扩展性,Mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓
存。
二级缓存-->一级缓存-->数据库