赞
踩
@Insert:实现新增
@Update:实现更新
@Delete:实现删除
@Select:实现查询
@Result:实现结果集封装
@Results:可以与@Result 一起使用,封装多个结果集
@ResultMap:实现引用@Results 定义的封装
@One:实现一对一结果集封装
@Many:实现一对多结果集封装
@SelectProvider: 实现动态 SQL 映射
@CacheNamespace:实现注解二级缓存的使用
<packaging>jar</packaging> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> </dependency> </dependencies>
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
<?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 文件的位置 --> <properties resource="jdbcConfig.properties"></properties> <!-- 配置别名的注册 --> <typeAliases> <package name="com.itheima.domain"/> </typeAliases> <!-- 配置环境 --> <environments default="mysql"> <!-- 配置 mysql 的环境 --> <environment id="mysql"> <!-- 配置事务的类型是 JDBC --> <transactionManager type="JDBC"></transactionManager> <!-- 配置数据源 --> <dataSource type="POOLED"> <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> </environments> <!-- 配置映射信息 --> <mappers> <package name="com.itheima.dao"/> </mappers> </configuration>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/myMybatis
jdbc.username=root
jdbc.password=12345678
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=debug, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
public interface IUserDao { /*查询所有用户*/ @Select("select * from user") //实现对结果集封装的配置,和xml中的resultMap标签功能一样 @Results(id="userMap", value= { @Result(id=true,column="id",property="userId"), @Result(column="username",property="userName"), @Result(column="sex",property="userSex"), @Result(column="address",property="userAddress"), @Result(column="birthday",property="userBirthday") }) List<User> findAll(); /*根据 id 查询一个用户*/ @Select("select * from user where id = #{uid} ") //实现引用@Results 定义的封装 @ResultMap("userMap") User findById(Integer userId); /*保存操作*/ //先保存后查询 @Insert("insert into user(username, sex, birthday, address)values(#{userName},#{userSex},#{userBirthday},#{userAddress})") @SelectKey(keyColumn = "id", keyProperty = "userId", resultType = Integer.class, before = false, statement = {"select last_insert_id()"}) int saveUser(User user); /*更新操作*/ @Update("update user set username=#{userName}, address =#{userAddress}, sex =#{userSex}, birthday =#{userBirthday}where id =#{userId}") int updateUser(User user); /*删除用户*/ @Delete("delete from user where id = #{userId} ") int deleteUser(Integer userId); /*查询使用聚合函数*/ @Select("select count(*) from user ") int findTotal(); /*模糊查询*/ @Select("select * from user where username like #{userName} ") List<User> findByName(String name); }
public class UserTest { private InputStream in; private SqlSessionFactory factory; private SqlSession session; private IUserDao userDao; @Before//junit 的注解 public void init()throws Exception{ //1.读取配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建工厂 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); factory = builder.build(in); //3.创建 session session = factory.openSession(); //4.创建代理对象 userDao = session.getMapper(IUserDao.class); } @After//junit 的注解 public void destroy()throws Exception { //提交事务 session.commit(); //释放资源 session.close(); //关闭流 in.close(); } /** * 测试查询所有 */ @Test public void testFindAll() { List<User> users = userDao.findAll(); for(User user : users) { System.out.println(user); } } /** * 测试查询一个 */ @Test public void testFindById() { User user = userDao.findById(41); System.out.println(user); } /** * 测试保存 */ @Test public void testSave() { User user = new User(); user.setUserName("mybatis annotation"); user.setUserSex("男"); user.setUserAddress("北京市顺义区"); user.setUserBirthday(new Date()); int res = userDao.saveUser(user); System.out.println("影响数据库记录的行数: "+res); System.out.println("插入的主键值: "+user.getUserId()); } /** * 测试更新 */ @Test public void testUpdate() { User user = userDao.findById(41); user.setUserBirthday(new Date()); user.setUserSex("女"); int res = userDao.updateUser(user); System.out.println(res); } /** * 测试删除 */ @Test public void testDelete() { int res = userDao.deleteUser(63); System.out.println(res); } /** * 测试查询使用聚合函数 */ @Test public void testFindTotal() { int res = userDao.findTotal(); System.out.println(res); } /** * 测试模糊查询 */ @Test public void testFindByName() { List<User> users = userDao.findByName("%m%"); for(User user : users) { System.out.println(user); } } }
@Results 注解 代替的是标签<resultMap> 该注解中可以使用单个@Result 注解,也可以使用@Result 集合 例如: @Results({@Result(), @Result() })或@Results(@Result()) @Resutl 注解 代替了 <id>标签和<result>标签 @Result 中属性介绍: id 是否是主键字段 column 数据库的列名 property 需要装配的属性名 one 需要使用的@One 注解(@Result(one=@One)())) many 需要使用的@Many 注解(@Result(many=@many)())) @One 注解(一对一) 代替了<assocation>标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。 @One 注解属性介绍: select 指定用来多表查询的 sqlmapper fetchType 会覆盖全局的配置参数 lazyLoadingEnabled。。 使用格式: @Result(column=" ",property="",one=@One(select="")) @Many 注解(多对一) 代替了<Collection>标签,是是多表查询的关键,在注解中用来指定子查询返回对象集合。 注意:聚集元素用来处理“一对多”的关系。需要指定映射的 Java 实体类的属性,属性的 javaType(一般为 ArrayList)但是注解中可以不定义; 使用格式: @Result(property="",column="",many=@Many(select=""))
private Integer id;
private Integer uid;
private Double money;
//多对一关系映射:从表方应该包含一个主表方的对象引用
private User user;
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
One:相当于association的配置
select 属性:代表将要执行的 sql 语句
fetchType 属性:代表加载方式,一般如果要延迟加载都设置为 LAZY 的值
public interface IAccountDao { /** * 查询所有账户,采用延迟加载的方式查询账户的所属用户 * @return */ @Select("select * from account") @Results(id="accountMap", value= { @Result(id=true,column="id",property="id"), @Result(column="uid",property="uid"), @Result(column="money",property="money"), @Result(column="uid", property="user", one=@One(select="com.aismall.dao.IUserDao.findById", fetchType=FetchType.LAZY ) ) }) List<Account> findAll(); }
public interface IUserDao { @Results(id="userMap", value= { @Result(id=true,column="id",property="userId"), @Result(column="username",property="userName"), @Result(column="sex",property="userSex"), @Result(column="address",property="userAddress"), @Result(column="birthday",property="userBirthday") }) /** * 根据 id 查询一个用户 * @param userId * @return */ @Select("select * from user where id = #{uid} ") //@ResultMap("userMap") User findById(Integer userId); }
public class AccountTest { private InputStream in; private SqlSessionFactory factory; private SqlSession session; private IAccountDao accountDao; @Before//junit 的注解 public void init()throws Exception{ //1.读取配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建工厂 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); factory = builder.build(in); //3.创建 session session = factory.openSession(); //4.创建代理对象 accountDao = session.getMapper(IAccountDao.class); } @After//junit 的注解 public void destroy()throws Exception { //提交事务 session.commit(); //释放资源 session.close(); //关闭流 in.close(); } @Test public void testFindAll() { List<Account> accounts = accountDao.findAll(); for (Account account:accounts){ System.out.println("------------"); System.out.println(account); System.out.println(account.getUser()); } } }
//一对多关系映射:主表方法应该包含一个从表方的集合引用
private List<Account> accounts;
@Many:相当于xml中的collection的配置
select 属性:代表将要执行的 sql 语句
fetchType 属性:代表加载方式,一般如果要延迟加载都设置为 LAZY 的值
1.添加在@Results标签中的value里面
@Result(column="id",property="accounts",
many=@Many(
select="com.aismall.dao.IAccountDao.findByUid",
fetchType=FetchType.LAZY
)
)
2.查询语句
@Select("select * from user")
@ResultMap("userMap")
List<User> findAll();
@Select("select * from account where uid = #{uid} ")
List<Account> findByUid(Integer userId);
public class UserTest { private InputStream in; private SqlSessionFactory factory; private SqlSession session; private IUserDao userDao; @Before//junit 的注解 public void init()throws Exception{ //1.读取配置文件 in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.创建工厂 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); factory = builder.build(in); //3.创建 session session = factory.openSession(); //4.创建代理对象 userDao = session.getMapper(IUserDao.class); } @After//junit 的注解 public void destroy()throws Exception { //提交事务 session.commit(); //释放资源 session.close(); //关闭流 in.close(); } /** * 测试查询所有 */ @Test public void testFindAll() { List<User> users = userDao.findAll(); for(User user : users) { System.out.println("-----每个用户的内容-----"); System.out.println(user); System.out.println(user.getAccounts()); } } }
<!-- 配置二级缓存 -->
<settings>
<!-- 开启二级缓存的支持 -->
<setting name="cacheEnabled" value="true"/>
</settings>
@CacheNamespace(blocking=true)//mybatis 基于注解方式实现配置二级缓存
public interface IUserDao {}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。