文章目录
1.limit分页
2.注解
3.mybatis执行流程
4.注解CRUD
5.Lombok
1.Limit分页
语法:
SELECT * from user limit startIndex,pageSize;
SELECT * from user limit 0,2;
package com.redeemi.dao;import com.redeemi.pojo.User;import java.util.List;
import java.util.Map;public interface UserMapper {//根据id查询用户User getUserById(int id);List<User> getUserByLimit(Map<String, Integer> map);}
xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace绑定一个对应的mapper接口-->
<mapper namespace="com.redeemi.dao.UserMapper"><select id="getUserById" resultMap="UserMap"parameterType="int">select * from mybatis.user where id = #{id}</select><!--结果集映射--><resultMap id="UserMap" type="User"><!--colunm 数据库中的字段,property实体中的属性--><!--<result column="id" property="id"></result>--><!--<result column="name" property="name"></result>--><result column="pwd" property="password"></result></resultMap><select id="getUserByLimit" parameterType="map"resultType="User" resultMap="UserMap">select * from mybatis.user limit #{startIndex},#{pageSize}</select></mapper>
test类
@Test
public void getByLimit(){SqlSession sqlSession = MybatisUtils.getSqlSession();UserMapper mapper = sqlSession.getMapper(UserMapper.class);Map<String, Integer> map = new HashMap<String, Integer>();map.put("startIndex", 1);map.put("pageSize", 2);List<User> userList = mapper.getUserByLimit(map);for(User user:userList){System.out.println(user);}sqlSession.close();
}
2.RowBounds分页
@Test
@Test
public void getUserByRow(){SqlSession sqlSession = MybatisUtils.getSqlSession();//RowBounds实现RowBounds rowBounds = new RowBounds(1, 2);//通过java代码层面List<User> userList = sqlSession.selectList("com.hou.dao.UserMapper.getUserByRowBounds",null,rowBounds);for (User user : userList) {System.out.println(user);}sqlSession.close();
}
3.分页插件
- pageHelper
2.使用注解开发
简单的语句可以使用注解,复杂的不要用,仅做了解
1.删除 UserMapper.xml
2.UserMapper
package com.redeemi.dao;import com.redeemi.pojo.User;
import org.apache.ibatis.annotations.Select;import java.util.List;public interface UserMapper {@Select("select * from user")List<User> getUsers();
}
核心配置 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!--引入外部配置文件--><properties resource="db.properties"/><!--可以给实体类起别名--><typeAliases><typeAlias type="com.redeemi.pojo.User" alias="User"></typeAlias></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC"/><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 class="com.redeemi.dao.UserMapper"></mapper></mappers>
</configuration>
本质:反射机制
底层:动态代理!
3.Mybatis详细执行流程
- Resource获取全局配置文件
- 实例化SqlsessionFactoryBuilde
- 解析配置文件流XMLCondigBuilder
- Configration所有的配置信息
- SqlSessionFactory实例化
- trasactional事务管理
- 创建executor执行器
- 创建SqlSession
- 实现CRUD
- 查看是否执行成功
- 提交事务
- 关闭
4.注解CRUD
package com.redeemi.dao;import com.redeemi.pojo.User;
import org.apache.ibatis.annotations.*;import java.util.List;public interface UserMapper {@Select("select * from user")List<User> getUsers();//方法存在多个参数,所有的参数必须加@Param@Select("select * from user where id = #{id}")User getUserById(@Param("id") int id);@Insert("insert into user (id, name, pwd) values" +"(#{id},#{name},#{password})")int addUser(User user);@Update("update user set name=#{name}, pwd=#{password} " +"where id=#{id}")int updateUser(User user);@Delete("delete from user where id=#{id}")int deleteUser(@Param("id") int id);}
MybatisUtils
package com.redeemi.utils;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 java.io.IOException;
import java.io.InputStream;//sqlSessionFactory --> sqlSession
public class MybatisUtils {private static SqlSessionFactory sqlSessionFactory;static {try {//使用mybatis第一步:获取sqlSessionFactory对象String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}public static SqlSession getSqlSession(){return sqlSessionFactory.openSession(true);}}
Test
package com.redeemi.dao;import com.redeemi.pojo.User;
import com.redeemi.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.List;public class UserDaoTest {@Testpublic void test(){// 获得sqlsession对象SqlSession sqlSession = MybatisUtils.getSqlSession();try{// 1.执行 getmapperUserMapper userDao = sqlSession.getMapper(UserMapper.class);List<User> userList = userDao.getUsers();for (User user : userList) {System.out.println(user);}}catch(Exception e){e.printStackTrace();}finally{//关闭sqlSession.close();}}@Testpublic void getuserById(){// 获得sqlsession对象SqlSession sqlSession = MybatisUtils.getSqlSession();try{// 1.执行 getmapperUserMapper userDao = sqlSession.getMapper(UserMapper.class);User user = userDao.getUserById(1);System.out.println(user);}catch(Exception e){e.printStackTrace();}finally{//关闭sqlSession.close();}}@Testpublic void addUser(){// 获得sqlsession对象SqlSession sqlSession = MybatisUtils.getSqlSession();try{// 1.执行 getmapperUserMapper userDao = sqlSession.getMapper(UserMapper.class);userDao.addUser(new User(6, "kun","123"));}catch(Exception e){e.printStackTrace();}finally{//关闭sqlSession.close();}}@Testpublic void updateUser(){// 获得sqlsession对象SqlSession sqlSession = MybatisUtils.getSqlSession();try{// 1.执行 getmapperUserMapper userDao = sqlSession.getMapper(UserMapper.class);userDao.updateUser(new User(6, "fang","123"));}catch(Exception e){e.printStackTrace();}finally{//关闭sqlSession.close();}}@Testpublic void deleteUser(){// 获得sqlsession对象SqlSession sqlSession = MybatisUtils.getSqlSession();try{// 1.执行 getmapperUserMapper userDao = sqlSession.getMapper(UserMapper.class);userDao.deleteUser(6);}catch(Exception e){e.printStackTrace();}finally{//关闭sqlSession.close();}}
}
5.Lombok
lombok用于通过注解简化实体类的方法(有参、无参、getset、tostring),可用可不用
1.在IDEA中安装lombok插件
2.配置
<dependencies><!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.12</version></dependency>
</dependencies>
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@Data: 无参构造,get,set,toString,hashCode
在实体类上加注解
package com.redeemi.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor //有参
@NoArgsConstructor //无参
public class User {private int id;private String name;private String password;}