Mybatis_day4_Mybatisのアノテーション開発

  • アノテーション開発は近年ますます人気があり、Mybatisもアノテーション開発を使用できるため、マッパーマッピングファイルの書き込みを減らすことができます。

Mybatis共通メモ

  • @Insert:新しい実装
  • @Update:更新の実装
  • @Delete:削除を実装する
  • @Select:クエリを実装する
  • @Result:結果セットのカプセル化を実装する
  • @Results:@Resultと共に使用して、複数の結果セットをカプセル化できます
  • @ResultMap:参照@Resultsによって定義されたカプセル化を実装します
  • @One:1対1の結果セットのカプセル化を実装する
  • @Many:1対多の結果セットのカプセル化を実装する
  • @SelectProvider:動的SQLマッピングを実装する
  • @CacheNamespace:注釈付き2次キャッシュの使用を実装する

Mybatisアノテーションを使用して基本的なCRUDを実装する

  1. エンティティクラスの記述
public class User implements Serializable {
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;

public Integer getUserId() {
	return userId;
}
public void setUserId(Integer userId) {
	this.userId = userId;
}
.....
  • 注:ここでのユーザーの属性名は、データベーステーブルの列名と一致していません。

  1. アノテーションを使用して永続化レイヤーインターフェイスを開発する
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@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 查询一个用户
* @param userId
* @return
*/
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);


/**
* 保存操作
* @param user
* @return
*/
@Insert("insert into user(username,sex,birthday,address)values(#{username},#{sex},#{birthday},#{address})")
int saveUser(User user);


/**
* 更新操作
* @param user
* @return
*/
@Update("update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id =#{id} ")
int updateUser(User user);


/**
* 删除用户
* @param userId
* @return
*/
@Delete("delete from user where id = #{uid} ")
int deleteUser(Integer userId);


/**
* 查询使用聚合函数
* @return
*/
@Select("select count(*) from user ")
int findTotal();

/**
* 模糊查询
* @param name
* @return
*/
@Select("select * from user where username like #{username} ")
List<User> findByName(String name);
}

  1. SqlMapConfig構成ファイルを書き込む

<!-- 配置映射信息 -->
<mappers>
	<!-- 配置 dao 接口的位置,它有两种方式
第一种:使用 mapper 标签配置 class 属性
第二种:使用 package 标签,直接指定 dao 接口所在的包
-->
	<package name="cn.myp666.dao"/>
</mappers>



アノテーションを使用して複雑な関係マッピング開発を実装する

  • 複雑なリレーションシップマッピングを実装する前に、マッピングファイルの設定を通じてそれを<resultMap>実現できます。アノテーションを使用して開発する場合は、@ Resultsアノテーション、@ Resultアノテーション、@ Oneアノテーション、@ Manyアノテーションを使用する必要があります。

複雑な関係マッピングの注釈の説明
  • @Results 注解

    • ラベルの代わりに<resultMap>
    • このアノテーションで単一の@Resultアノテーションを使用するか、@ Resultコレクションを使用できます
      • @Results({@ Result()、@ Result()})または@Results(@Result())
  • @Result 注解

    • <id>タグと<result>タグを置き換える
    • @Resultの属性の概要:
      • idは主キーフィールドです
      • columnデータベースの列名
      • property組み立てられるプロパティの名前
      • 使用する1つの@Oneアノテーション(@Result(one = @ One)()))
      • 使用する多くの@Manyアノテーション(@Result(many = @ many)()))
  • @One注解(1対1)

    • <assocation>ラベルの代わりに、これはマルチテーブルクエリのキーであり、サブクエリが単一のオブジェクトを返すことを指定するために注釈で使用されます。
    • @Oneアノテーション属性の紹介:
      • selectは、マルチテーブルクエリに使用されるsqlmapperを指定します
      • fetchTypeはグローバル構成パラメーターをオーバーライドします
      • lazyLoadingEnabled。。
    • 形式を使用:
      • @Result(column = "“、property =”“、one = @ One(select =”"))
  • @Many注解(1対多)

    • <Collection>ラベルの代わりに、これはマルチテーブルクエリの鍵であり、サブクエリがオブジェクトのコレクションを返すことを指定するために注釈で使用されます。
    • 注:集約要素は、「1対多」の関係を処理するために使用されます。マップされたJavaエンティティークラスの属性、属性のjavaType(通常はArrayList)を指定する必要がありますが、アノテーションで定義することはできません。
    • 形式を使用:
      • @Result(property = "“、column =”“、many = @ Many(select =”"))

注釈を使用した1対多の複雑な関係マッピング
  1. アカウントの永続化レイヤーインターフェイスを追加し、注釈構成を使用する
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="cn.myp666.dao.IUserDao.findById",fetchType=FetchType.LAZY)
)
})
List<Account> findAll();
}

  1. ユーザーの永続化レイヤーインターフェイスを追加し、注釈構成を使用する
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@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 查询一个用户
* @param userId
* @return
*/
@Select("select * from user where id = #{uid} ")
@ResultMap("userMap")
User findById(Integer userId);
}


注釈を使用した1対多の複雑な関係マッピング
  1. ユーザー永続性レイヤーインターフェイスを記述し、注釈構成を使用する
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
@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"),
		@Result(column="id",
				property="accounts",
				many=@Many(select="cn.myp666.dao.IAccountDao.findByUid",
				fetchType=FetchType.LAZY)
				)
			}
		)
	List<User> findAll();
}
  • @Many:同等の<collection>構成
  • select属性:実行されるSQLステートメントを表します
  • fetchType属性:読み込みメソッドを表します。通常、読み込みを遅らせたい場合LAZYは値に設定します

  1. アカウントの永続化レイヤーインターフェイスを記述し、注釈構成を使用する
public interface IAccountDao {
/**
* 根据用户 id 查询用户下的所有账户
* * @param userId
* @return
*/
@Select("select * from account where uid = #{uid} ")
List<Account> findByUid(Integer userId);
}



mybatis注釈付き2次キャッシュ

  1. SqlMapConfigで二次キャッシュのサポートを有効にする
<!-- 配置二级缓存 -->
<settings>
<!-- 开启二级缓存的支持 -->
	<setting name="cacheEnabled" value="true"/>
</settings>
  1. アノテーションを使用して永続化レイヤーインターフェイスで2次キャッシュを構成する
@CacheNamespace(blocking=true)//mybatis 基于注解方式实现配置二级缓存
public interface IUserDao {}
元の記事94件を公開 称賛された0 2097を訪問

おすすめ

転載: blog.csdn.net/qq_16836791/article/details/104802600