MyBatis(三、注解开发)

2年前 (2022) 程序员胖胖胖虎阿
371 0 0

作者:大三的土狗

专栏:SSM 框架
MyBatis(三、注解开发)

导航

    • 1、MyBatis的常用注解
    • 2、MyBatis注解方式的增删改查
    • 3、MyBatis的注解实现复杂映射
    • 4、Mybatis注解开发步骤
        • 1.导入maven依赖:
        • 2.数据库信息:
        • 3.编写日志配置文件:
        • 4.编写配置文件:
        • 5.编写pojo类和Mapper接口:
        • 6.编写测试类:

1、MyBatis的常用注解

  这几年来注解开发越来越流行,Mybatis也可以使用注解开发方式,这样我们就可以减少编写Mapper 映射文件了。
MyBatis(三、注解开发)

  • @Insert:实现新增
  • @Update:实现更新
  • @Delete:实现删除
  • @Select:实现查询
  • @Result:实现结果集封装
  • @Results:可以与@Result 一起使用,封装多个结果集
  • @One:实现一对一结果集封装
  • @Many:实现一对多结果集封装

2、MyBatis注解方式的增删改查

​ 修改MyBatis的核心配置文件,我们使用了注解替代的映射文件,所以我们只需要加载使用了注解的Mapper接口即可。

   <!--加载映射关系-->
    <mappers>
        <!--指定接口所在的包-->
        <package name="com.xmp.mapper"></package>
    </mappers>

@Insert("insert into user values(#{id},#{username},#{password},#{birthday})")
public void save(User user);
@Update("update user set username=#{username},password=#{password} where id=#{id}")
public void update(User user);
@Delete("delete from user where id=#{id}")
public void delete(int id);
@Select("select * from user where id=#{id}")
public User findById(int id);

@Select("select * from user")
public List<User> findAll();

3、MyBatis的注解实现复杂映射

  实现复杂关系映射之前我们可以在映射文件中通过配置来实现,使用注解开发后,我们可以使用@Results注解 ,@Result注解,@One注解,@Many注解组合完成复杂关系的配置。

注解 说明
@Results 代替的是标签该注解中可以使用单个@Result注解,也可以使用@Result集 合。使用格式:@Results({@Result(),@Result()})或@Results(@Result())
@Resut 代替了标签和标签 @Result中属性介绍: column:数据库的列名 property:需要装配的属性名 one:需要使用的@One 注解(@Result(one=@One)())) many:需要使用的@Many 注解(@Result(many=@many)()))
@One (一对一) 代替了 标签,是多表查询的关键,在注解中用来指定子查询返回单一对象。 @One注解属性介绍: select: 指定用来多表查询的 sqlmapper 使用格式:@Result(column=" “,property=”“,one=@One(select=”"))
@Many (多对一) 代替了标签, 是是多表查询的关键,在注解中用来指定子查询返回对象集合。 使用格式:@Result(property=“”,column=“”,many=@Many(select=“”))

4、Mybatis注解开发步骤

1.导入maven依赖:

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.objectweb.asm/org.objectweb.asm -->
    <dependency>
        <groupId>org.objectweb.asm</groupId>
        <artifactId>org.objectweb.asm</artifactId>
        <version>3.3.1.v201105211655</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/cglib/cglib -->
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.2.8</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core -->
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache-core</artifactId>
        <version>2.6.11</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
    <dependency>
        <groupId>org.javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.23.1-GA</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.11.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.11.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
    <dependency>
        <groupId>org.mybatis.caches</groupId>
        <artifactId>mybatis-ehcache</artifactId>
        <version>1.1.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.12</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.8.0-beta2</version>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.8.0-beta2</version>
    </dependency>

</dependencies>

2.数据库信息:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.passwords=root

3.编写日志配置文件:

##将等级为INFO的日志信息输出到stdout和R这两个目的
log4j.rootCategory=INFO, stdout , R   
 
#日志输出到控制台--   log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
#日志布局样式-自定义样式 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout   
#日志样式
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n   
 
##日志到每天一个日志文件    
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
##日志输出地址
log4j.appender.R.File=D:\\my.log  
#日志布局样式-自定义样式  
log4j.appender.R.layout=org.apache.log4j.PatternLayout  
#日志样式 
1log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n   
 
   ##下面是指定具体的包下面的所有日志的级别
log4j.logger.com.neusoft=DEBUG   
log4j.logger.com.opensymphony.oscache=ERROR   
log4j.logger.net.sf.navigator=ERROR   
log4j.logger.org.apache.commons=ERROR   
log4j.logger.org.apache.struts=WARN   
log4j.logger.org.displaytag=ERROR   
log4j.logger.org.springframework=DEBUG   
log4j.logger.com.ibatis.db=WARN   
log4j.logger.org.apache.velocity=FATAL   

4.编写配置文件:

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="db.properties"></properties>
    <settings>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
        <setting name="cacheEnabled" value="true"></setting>
    </settings>
    <typeAliases><!--别名-->
        <!--<typeAlias type="com.xmp.entity.User" alias="user"></typeAlias>-->
        <package name="com.xmp..pojo"></package>

    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--<mapper resource="sqlmap/User.xml"></mapper>-->
        <!--<mapper resource="mapper/UserMapper.xml"></mapper>-->
        <!--Mapper接口和映射文件必须在同一文件夹下  遵循规范
        <mapper class="com.xmp..mapper.UserMapper"></mapper>-->
        <!--Mapper接口的包名,自动扫描。遵循规范
        <package name=""></package>-->
        <package name="com.xmp.mapper"></package>
        <package name="com.xmp.pojo"></package>
    </mappers>

</configuration>

5.编写pojo类和Mapper接口:

@Mapper
public interface UserMapper {
    @Select("select * from user where id=#{id}")
    public User getUserById(Integer id);

    @Delete("delete from user where id=#{id}")
    public void deleteUserById(Integer id);

    @Insert("insert user(id,username,birthday,sex,address) value(#{id},#{username},#{birthday},#{sex},#{address})")
    public void addUser(User user);

    @Update("update user set id=#{id},username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}")
    public void updateUser(User user);
}
public class User {
    private int id;
    private String username;
    private Date birthday;
    private Integer sex;
    private String address;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday(Date date) {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex=" + sex +
                ", address='" + address + '\'' +
                '}';
    }
}

6.编写测试类:

public class UserMapperTest {
    SqlSessionFactory sqlSessionFactory;
    @Before
    public void setUp() throws Exception {
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //初始化mybatis,创建SqlSessionFactory类的实例
        sqlSessionFactory =  new SqlSessionFactoryBuilder().build(resourceAsStream);
    }

    @Test
    public void getUserById() {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User userById = userMapper.getUserById(10);
        System.out.println("Message="+userById);
    }


    @Test
    public void deleteUserById() {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        userMapper.deleteUserById(26);
    }

    @Test
    public void addUser() {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User user=new User();
        user.setId(30);
        user.setUsername("xmp");
        user.setBirthday(new Date());
        user.setAddress("SH");
        userMapper.addUser(user);
        sqlSession.commit();
    }

    @Test
    public void updateUser() {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        User userById = userMapper.getUserById(1);
        userById.setBirthday(new Date());
        userById.setAddress("广西柳州");
        userMapper.updateUser(userById);
        sqlSession.commit();
    }
}

版权声明:程序员胖胖胖虎阿 发表于 2022年9月7日 下午3:56。
转载请注明:MyBatis(三、注解开发) | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...