什么是框架?
它是我们软件开发中的一套解决方案,不同的框架解决的是不同的问题。
使用框架的好处:
框架封装了很多细节,使开发者可以使用极简的方式实现功能。大大提高开发效率。
三层架构
表现层:展示数据
业务层:处理业务需求的
持久层:和数据库交互的
持久层技术解决方案
JDBC技术:
- Connection
- PreparedStatement
- ResultSet
Spring的JdbcTemplate
Spring中对jdbc的简单封装
Apache的DBUtils:
也是简单封装
都不是框架,JDBC是规范,JdbcTemplate和DBUtils只是工具类
Mybatis
是一个持久层框架,用java写的
封装了jdbc操作的很多细节,使开发者只需要关注sql语句本身,而无需关注注册驱动,创建连接等繁杂过程,它使用了ORM思想实现了结果集的封装
ORM
Object Relational Mappging 对象关系映射
简单的说,就是把数据库表和实体类的属性对应起来,让我们可以操作实体类就实现操作数据库表。
mybatis的入门
mybatis的环境搭建
- 创建maven工程并导入坐标
- 创建实体类和dao的接口
- 创建Mybatis的主配置文件SqlMapConfig.xml
- 创建映射的配置文件IUserDao.xml
注意事项:
- 创建IUserDao.xml以及IuserDao.java时,名称可以这么写。在Mybatis中它把吃就成的操作接口名称和映射文件也叫做Mapper,故IUserDao和IUserMapper是一样的。
- idea中创建目录时,它和包是不一样的
- mybatis的映射配置文件位置必须和dao的包结构相同
- 映射配置文件的mapper标签namespace属性的取值必须是dao接口的全限定类名
- 映射欸之文件的操作配置,id接口的曲子必须是dao接口的方法名
如:主配置文件:
<?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">
<!--配置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/mybatis_user?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<mappers>
<mapper resource="com/huangyy/dao/IUserDao.xml"></mapper>
</mappers>
</configuration>
映射配置文件:
<?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="cn.huangyy.dao.IUserDao">
<select id="findAll" resultType="cn.huangyy.domain.User">
select * from mybatis_user ;
</select>
</mapper>
Mybatis案例
public class MybatisTest {
public static void main(String[] args) throws IOException {
// 读取配置文件
InputStream in= Resources.getResourceAsStream("SqlMapConfig.xml");
// 创建SqlSessionFactory工厂
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
SqlSessionFactory factory=builder.build(in);
// 使用工厂生产SqlSession对象
SqlSession session=factory.openSession();
// 使用SqlSession创建Dao接口的代理对象
IUserDao userDao=session.getMapper(IUserDao.class);
// 使用代理对象执行方法
List<User> users= userDao.findAll();
for (User user : users) {
System.out.println(user);
}
// 释放资源
session.close();
in.close();
}
}
注解配置代替映射的配置文件
public interface IUserDao {
@Select("select * from mybatis_user")
List<User> findAll();
}
主配置文件中:
<mappers>
<mapper class="cn.huangyy.dao.IUserDao"></mapper>
</mappers>
我们在实际开发中,都是越简便越好,所以都是采用不写dao实现类的方式,不管使用XML还是注解配置。
但是Mybatis它是支持写dao实现类的
增删改查练习
UserDao接口:
public interface UserDao {
List<User> findAll();
void saveUser(User user);
void updateUser(User user);
void deleteUser(Integer uid);
User findById(Integer uid);
List<User> findByName(String username);
int findTotal();
}
UserDao.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">
<mapper namespace="cn.huangyy.dao.UserDao">
<select id="findAll" resultType="cn.huangyy.domain.User">
select * from mybatis_user;
</select>
<insert id="saveUser" parameterType="cn.huangyy.domain.User">
insert into mybatis_user values (null,#{username},#{birthday},#{sex},#{address});
</insert>
<update id="updateUser" parameterType="cn.huangyy.domain.User">
update mybatis_user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id};
</update>
<delete id="deleteUser" parameterType="Integer">
delete from mybatis_user where id=#{uid};
</delete>
<select id="findById" resultType="cn.huangyy.domain.User" parameterType="java.lang.Integer">
select * from mybatis_user where id=#{uid}
</select>
<select id="findByName" resultType="cn.huangyy.domain.User" parameterType="java.lang.String">
<!--select * from mybatis_user where username like #{user};*/-->
select * from mybatis_user where username like '%${value}%';
</select>
<select id="findTotal" resultType="java.lang.Integer">
select count(id) from mybatis_user;
</select>
</mapper>
模糊查询中注意:
select * from mybatis_user where username like #{user};
底层用的是preparedStatementselect * from mybatis_user where username like '%${value}%';
底层用的是Statement
test类:
public class MybatisTest {
private InputStream in;
private SqlSession session;
private UserDao userDao;
@Before
public void init() throws IOException {
in= Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
session = factory.openSession();
userDao = session.getMapper(UserDao.class);
}
@After
public void destroy() throws IOException {
session.commit();
session.close();
in.close();
}
@Test
public void testFindAll() throws IOException {
List<User> list = userDao.findAll();
for (User user : list) {
System.out.println(user);
}
}
@Test
public void testSave(){
User user=new User();
user.setUsername("哇哈哈");
user.setAddress("朝南");
user.setSex("女");
user.setBirthday(new Date());
userDao.saveUser(user);
}
@Test
public void testUpdate(){
User user=new User();
user.setId(2);
user.setUsername("牛皮");
user.setAddress("朝南");
user.setSex("男");
user.setBirthday(new Date());
userDao.updateUser(user);
}
@Test
public void testDelete(){
userDao.deleteUser(10);
}
@Test
public void testFindById(){
User user = userDao.findById(2);
System.out.println(user);
}
@Test
public void testFindByName(){
List<User> list = userDao.findByName("王");
for (User user : list) {
System.out.println(user);
}
}
@Test
public void testFindTotal(){
int total = userDao.findTotal();
System.out.println(total);
}
}
OGNL表达式
Object Graphic Navigation Language 对象 图 导航 语言
它是通过对象的取值方法来过去数据。在写法上把get给省略了。
比如我们获取用户的名称
类中的写法:user.getUsername();
OGNL表达式:user.username
mybatis中为什么能直接写username。而不是user呢?因为在parameterType中已经提供了属性所属的类,所以此时不需要写对象名
实体类属性和数据库中属性名不一致
解决方法:
1.可以在sql语句中起别名:
如实体类中是userId,而数据库中是id,则可这么查询:select id as userId from mybatis_user
2.可以在UserDao.xml中配置:
如:
<resultMap id="userMap" type="cn.huangyy.domain.User">
<!--主键字段的对应-->
<id property="userId" column="id"></id>
<!--非键字段的对应-->
<result property="userAddress" column="address"></result>
</resultMap>
<select id="findAll" resultMap="userMap">
select * from mybatis_user;
</select>
若自己写Dao的实现类
findAll举例:
public class UserDaoImpl implements UserDao {
private SqlSessionFactory factory;
public UserDaoImpl(SqlSessionFactory factory) {
this.factory = factory;
}
@Override
public List<User> findAll() {
SqlSession session=factory.openSession();
List<User> list = session.selectList("cn.huangyy.dao.UserDao.findAll");
session.close();
return list;
}
}
配置properties标签
可以在标签内部配置连接数据库的信息,也可以通过属性引用外部配置文件信息
1.resource属性
用于指定配置文件的位置,是按照类路径的写法来写,并且必须存在于类路径下。
jdbcConfig.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_test?useSSL=false
username=root
password=123456
SqlMapConfig.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>
<properties resource="jdbcConfig.properties"></properties>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="cn/huangyy/dao/UserDao.xml"></mapper>
</mappers>
</configuration>
2.url属性:
是要求按照url的写法来写地址
URL:Uniform Resource Locator 统一资源定位符。它是可以唯一标识一个资源的位置
如:http://localhost:8080/mybatisserver/demo1Servlet
如:
<properties url="file:///C:/Users/Huangyy/Desktop/jdbcConfig.properties"></properties>
URI:Uniform Resource Identifier 统一资源标识符,它是应用中可以唯一定位一个资源的
配置typeAliases标签
typeAlias用于配置别名。type属性指定的是实体类全限定类名。alias属性指定别名,当指定了别名就不再区分大小写
<typeAliases>
<typeAlias type="cn.huangyy.domain.User" alias="user"></typeAlias>
</typeAliases>
package用于指定要配置别名的包,当指定后,该包下的实体类都会注册别名,并且类名就是别名,不再区分大小写
<typeAliases>
<package name="cn.huangyy.domain"/>
</typeAliases>
mappers标签中的package标签,用于指定dao接口所在的包,当制定了之后就不需要再写mapper以及resource或者class了
<mappers>
<package name="cn.huangyy.dao"/>
</mappers>
mybatis中的连接池
提供了3种方式的配置
配置的位置: 主配置文件SqlMapConfig.xml中的dataSource标签
Type属性的取值:
- POOLED:采用传统的javax.sql.DataSource规范中的连接池
- UNPOOLED:采用传统的获取连接的方式,虽说也实现了javax.sql.DataSource接口,但是并没有使用池的思想。
- JNDI:采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到的是不同的。注意:如果不是web或者是maven的war工程,是不能使用的。我们使用的tomcat服务器,采用的连接池就是dbcp连接池
mybatis中的事务控制
手动将它的事务提交方式改为自动提交:SqlSession session=sqlSessionFactory.openSession(true);
动态SQL标签
<if>
:
<select id="findByCondition" resultMap="userMap" parameterType="user">
select * from mybatis_user where 1=1
<if test="username!=null">
and username =#{username}
</if>
<if test="id!=null">
and id=#{id}
</if>
</select>
<where>
:
<select id="findByCondition" resultMap="userMap" parameterType="user">
select * from mybatis_user
<where>
<if test="username!=null">
and username =#{username}
</if>
<if test="id!=null">
and id=#{id}
</if>
</where>
</select>
<foreach>
:
<select id="findUserInIds" resultMap="userMap" parameterType="queryvo">
select * from mybatis_user
<where>
<if test="ids!=null and ids.size()>0">
<foreach collection="ids" open="and id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
了解内容:
抽取重复的sql语句
<sql>
与<include>
标签:
<sql id="defaultUser">
select * from mybatis_user
</sql>
<select id="findAll" resultMap="userMap">
<include refid="defaultUser"></include>
</select>
Mybatis中的多表查询
事例:
用户和账户
一个用户可以有多个账户
一个账户只能属于一个用户(多个账户也可以属于同一个用户)
步骤:
先建立两张表:用户表、账户表
建立两个实体类:用户实体类、账户实体类
让用户表和账户表之间具备一对多的关系:需要使用外键在账户表中添加
建立两个配置文件:用户的配置文件和账户的配置文件
实现配置:当我们查询用户时,可以同时得到用户下所包含的账户信息,当我们查询账户时,可以同时得到账户的所属用户信息
查询账户:
AccountDao.xml:
<resultMap id="accountUserMap" type="account">
<id property="id" column="aid"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<association property="user" column="uid" javaType="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
</association>
</resultMap>
<select id="findAllAccountUser" resultMap="accountUserMap">
select u.username,a.id as aid,a.uid,a.money from mybatis2_user u,mybatis2_account a where u.id=a.uid
</select>
测试方法:
@Test
public void testFindAllAccUser(){
List<Account> accounts = accountDao.findAllAccountUser();
for (Account account : accounts) {
System.out.println("Account{id="+account.getId()+",money="+account.getMoney()+"uid="+account.getUid()+","+
",username"+account.getUser().getUsername()+"}");
}
}
查询用户:
UserDao.xml:
<resultMap id="userAccMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<collection property="accounts" ofType="account">
<id property="id" column="aid"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
</collection>
</resultMap>
<select id="findAllUserAcc" resultMap="userAccMap">
select u.*,a.money,a.id as aid from mybatis2_user u left join mybatis2_account a on u.id=a.uid
</select>
测试方法:
@Test
public void testFindAllUserAcc(){
List<User> users = userDao.findAllUserAcc();
for (User user : users) {
List<Account> accounts = user.getAccounts();
StringBuilder sb=new StringBuilder("account(");
for (Account account : accounts) {
sb.append("aid:"+account.getId()+"=>"+account.getMoney()+"元;");
}
sb.append(")");
System.out.println("User{id="+user.getId()+",username"+user.getUsername()+","+sb.toString());
}
}
多对多的查询:
用户和角色之间:
用户表:
角色表:
对应中间表:
这里拿查询用户举例:
UserDao.xml:
<mapper namespace="cn.huangyy.dao.UserDao">
<resultMap id="userMap" type="user">
<id property="id" column="id"></id>
<result property="username" column="username"></result>
<result property="sex" column="sex"></result>
<collection property="roles" ofType="role">
<id property="roleId" column="rid"></id>
<result property="roleName" column="rolename"></result>
</collection>
</resultMap>
<select id="findAll" resultMap="userMap">
select u.*,r.rolename from mybatis3_user u
left join mybatis3_role_user ru on u.id=ru.uid
left join mybatis3_role r on ru.rid=r.id
</select>
</mapper>
测试方法:
@Test
public void testFindAllUser(){
List<User> users = userDao.findAll();
for (User user : users) {
StringBuilder sb=new StringBuilder();
sb.append("user{uid=");
sb.append(user.getId());
sb.append(",username=");
sb.append(user.getUsername());
sb.append(",sex=");
sb.append(user.getSex());
sb.append(",roles(");
List<Role> roles = user.getRoles();
if (roles.size()>0||roles!=null){
for (Role role : roles) {
sb.append(role.getRoleName()+";");
}
}
sb.append(")}");
System.out.println(sb.toString());
}
}
结果:
JNDI数据源
Java Naming and Directory Interface
目录结构:
context.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<Context>
<!--name可随意取-->
<Resource
name="jdbc/eesy_mybatis"
type="javax.sql.DataSource"
auth="Container"
maxActive="20"
maxWait="10000"
maxIdle="5"
username="root"
password="1234"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/db_test?useSSL=false"
/>
</Context>
SqlMapConfig.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="cn.huangyy.domain"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="JNDI">
<property name="data_source" value="java:comp/env/jdbc/eesy_mybatis"/>
</dataSource>
</environment>
</environments>
</configuration>
Mybatis的延迟加载
延迟加载:
在真正使用数据时才发起查询,不用的时候就不查询。按需加载(懒加载)。一般在一对多和多对多中使用。
立即加载:
不管用不用,只要一调用方法,马上发起查询。一般在一对一和多对一中使用。
拿用户账户举例:
AccountDao.xml:
<mapper namespace="cn.huangyy.dao.AccountDao">
<resultMap id="accountUserMap" type="account">
<id property="id" column="id"></id>
<result property="uid" column="uid"></result>
<result property="money" column="money"></result>
<!--findById会根据uid去查,column属性不可省略-->
<association property="user" column="uid" javaType="user" select="cn.huangyy.dao.UserDao.findById">
</association>
</resultMap>
<select id="findAllAccountUser" resultMap="accountUserMap">
select * from mybatis2_account
</select>
</mapper>
SqlMapConfig.xml中的配置:
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
Mybatis中的缓存
缓存: 存在内存中的临时数据
作用: 减少和数据库的交互次数,提高执行效率
Mybatis中的一级缓存和二级缓存:
一级缓存:
指的是Mybatis中SqlSession对象的缓存。
当我们执行查询之后,查询的结果会同时存入到SqlSession为我们提供的一块区域中,该区域的结构是一个Map。当我们在此查询相同的数据,mybatis会先去sqlsession中查询是否有,有的话直接拿出来用。
当SqlSession有修改,添加,删除,commit(),close()等方法时,一级缓存则会被清空。
二级缓存:
指的是Mybatis中SqlSessionFactory对象的缓存。由同一个SqlSessionFactory对象创建的SqlSession共享其缓存。
二级缓存的使用步骤:
- 让Mybatis框架中支持二级缓存(在SqlMapConfig.xml中配置
<setting name="cacheEnabled" value="true"/>
) - 让当前的映射文件支持二级缓存(在UserDao.xml中配置
<cache/>
) - 让当前的操作支持二级缓存(在select标签中配置
useCache="true"
)
二级缓存中存的是数据而不是对象
Mybatis的注解开发
在mybatis中针对CRUD一共有4个注解
@Select
@Insert
@Update
@Delete
xml和注解两个方法不能同时使用,会报错
单表操作:
例:
@Select("select * from mybatis3_user")
List<User> findAll();
@Insert("insert into mybatis3_user values(null,#{username},#{sex})")
void saveUser(User user);
@Update("update mybatis3_user set username=#{username},sex=#{sex} where id=#{id}")
void updateUser(User user);
若属性名和数据库中的不同,可用该方式:
@Select("select * from mybatis3_user")
@Results(id = "userMap",value = {
@Result(id = true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "sex",property = "userSex")
})
其中id属性可让其可复用,使用:@ResultMap(value = {"userMap"})
多表查询:
利用延迟加载的思想:
多对一(一对一):
public interface AccountDao {
@Select("select * from mybatis2_account")
@Results(id = "accountMap",value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "uid",property = "uid"),
@Result(column = "money",property = "money"),
@Result(property = "user",column ="uid",one = @One(select = "cn.huangyy.dao.UserDao.findById",fetchType = FetchType.EAGER))
})
List<Account> findAll();
}
一对多(多对多):
@Select("select * from mybatis2_user")
@Results(id = "userMap",value = {
@Result(id = true,column = "id",property = "id"),
@Result(column = "username",property = "username"),
@Result(property = "accounts",column = "id",many = @Many(select = "cn.huangyy.dao.AccountDao.findByUid",fetchType = FetchType.LAZY))
})
List<User> findAll();
注解缓存配置
一级缓存自动开启
二级缓存配置:
第一步一样,先配置SqlMapConfig.xml
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
第二步,在dao接口上配置注解:
@CacheNamespace(blocking = true)
public interface UserDao {