Java教程

Mybatis注解开发

本文主要是介绍Mybatis注解开发,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

开头

注解开发的主配置文件仍旧与之前相同,注解开发是面向于dao的。
某个dao只能使用注解开发,或配置文件中的一种,不能同时使用
但可以ADao使用注解开发,BDao使用配置文件开发

一、简单的增删改查

package com.czy.dao;

import com.czy.domain.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface UserDao {
    /**
     * 查询所有用户
     * @return
     */
    @Select("select * from user")
    List<User> findAll();

    /**
     * 保存用户
     * @param user
     */
    @Insert("insert into user(username,address,sex,birthday) values(#{username},#{address},#{sex},#{birthday})")
    void saveUser(User user);

    @Update("update user set username = #{username},address = #{address},sex = #{sex},birthday = #{birthday} where id = #{id}")
    void updateUser(User user);

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

    @Select("select * from user where id = #{id}")
    User findById(Integer id);

    @Select("select * from user where username like '%${value}%'")
    List<User> findUserByName(String name);

    @Select("select count(*) from user")
    int findTotalUser();
}

二、注解实现复杂关系映射开发

1、属性和数据库列不对应关系(ResultMap)

    /**
     * 查询所有用户
     * @return
     */
    @Select("select * from user")
    @Results(value= {
            @Result(id=true ,column = "id", property = "userId"),
            @Result(column = "username", property = "userName"),
            @Result(column = "address", property = "userAddress"),
            @Result(column = "sex", property = "userSex"),
            @Result(column = "birthday", property = "userBirthday")
    },id="userMap"
    )
    List<User> findAll();


    @Select("select * from user where id = #{id}")
    @ResultMap({"userMap"})
    User findById(Integer id);

Results注解源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.apache.ibatis.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Results {
    String id() default "";

    Result[] value() default {};
}

Result注解源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.apache.ibatis.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.UnknownTypeHandler;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface Result {
    boolean id() default false;

    String column() default "";

    String property() default "";

    Class<?> javaType() default void.class;

    JdbcType jdbcType() default JdbcType.UNDEFINED;

    Class<? extends TypeHandler> typeHandler() default UnknownTypeHandler.class;

    One one() default @One;

    Many many() default @Many;
}

ResultMap注解源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.apache.ibatis.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ResultMap {
    String[] value();
}

2、多表查询

一个用户可以有多个账户,每个账户对应单个用户
多对一(mybatis中的一对一)
自我实现

    /**
     * 查询所有账户并获取其所属的用户信息
     * @return
     */
    @Select("select user.*, a.id aid, a.uid uid,a.money money from account a,user where a.uid = user.id")
    @Results(id = "accountMap",value = {
            @Result(id = true,column = "aid",property = "id"),
            @Result(column = "uid",property = "uid"),
            @Result(column = "money",property = "money"),
            @Result(column = "id",property = "user.userId"),
            @Result(column = "username",property = "user.userName"),
            @Result(column = "address",property = "user.userAddress"),
            @Result(column = "sex",property = "user.userSex"),
            @Result(column = "birthday",property = "user.userBirthday")
    })
    List<Account> findAll();

mybatis封装实现

    /**
     * 查询所有账户并获取其所属的用户信息
     * @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(property = "user",column = "uid",one = @One(select = "com.czy.dao.UserDao.findById",fetchType = FetchType.EAGER))
    })
    List<Account> findAll();

通过one标签实现
one标签源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.apache.ibatis.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.apache.ibatis.mapping.FetchType;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface One {
    String select() default "";

    FetchType fetchType() default FetchType.DEFAULT;
}

其中的Fetch即为预加载(lazy)和立即加载(eager)的设置

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.apache.ibatis.mapping;

public enum FetchType {
    LAZY,
    EAGER,
    DEFAULT;

    private FetchType() {
    }
}

一对多

  @Select("select * from user")
    @Results(value= {
            @Result(id=true ,column = "id", property = "userId"),
            @Result(column = "username", property = "userName"),
            @Result(column = "address", property = "userAddress"),
            @Result(column = "sex", property = "userSex"),
            @Result(column = "birthday", property = "userBirthday"),
            @Result(property = "accounts",column = "id",many = @Many(select = "com.czy.dao.AccountDao.findByUid",fetchType = FetchType.LAZY))
    },id="userMap"
    )
    List<User> findAll();

many源码类似于One

这篇关于Mybatis注解开发的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!