@Convert 注解在jpa中进行查询的注意事项

仅仅只作为java bean 中属性和数据库存储的映射

1.1 、convert实现

package com.chayiges;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.time.YearMonth;

/**
 * 使用 JPA 将 YearMonth 持久化为整数
 *
 * @author chayiges
 */
@Converter
public class YearMonthIntegerAttributeConverter 
                            implements AttributeConverter<YearMonth, Integer> {

	/**
	 * 实体类 -> 数据库
     * 向数据库中保存时调用
	 */
	@Override
	public Integer convertToDatabaseColumn(YearMonth yearMonth) {
		if (yearMonth!= null) {
			return (yearMonth.getYear() * 100) + yearMonth.getMonth().getValue();
		}
		return null;
	}

	/**
	 * 数据库 -> 实体类
     * 向数据库中查询时调用
	 */
	@Override
	public YearMonth convertToEntityAttribute(Integer integer) {
		if (integer!= null) {
			int year = integer / 100;
			int month = integer % 100;
			return YearMonth.of(year, month);
		}
		return null;
	}

}

1.2、创建数据库对应的实体类

package com.chayiges;

import org.jmolecules.ddd.types.AggregateRoot;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.time.YearMonth;
import java.util.UUID;

/**
 * 学生表对应的实体类
 *
 * @author chayiges
 */
@Entity
@Getter
@Table
@NoArgsConstructor(access = AccessLevel.PROTECTED, force = true)
@AllArgsConstructor
public class Student implements AggregateRoot<Student, UUID>,Serializable {


	/** ID */
	@EmbeddedId
	private UUID id;

	/** 姓名 */
	@Column(name = "user_name", length = 100, nullable = false)
	private String userName;

	/** 年月 */
	@Convert(converter = YearMonthIntegerAttributeConverter.class)
	@Column(name = "year_month")
	private YearMonth yearMonth;

}

1.3、jpa 查询

package com.chayiges;

import org.springframework.data.jpa.repository.JpaRepository;

import java.time.YearMonth;
import java.util.UUID;

/**
 * 学生表的jap查询
 *
 * @author chayiges
 */
public interface Students extends JpaRepository<Student, UUID> {

	/**
	 * 根据年月查询学生表
	 * @param yearMonth 年月
	 * @return 学生表
	 */
	List<Student> findByYearMonth(YearMonth yearMonth);

}

注意:此处查询年月的时候用的是 YearMonth 类型,并不是转换到数据中的Integer类型

所犯的错误可能如下

package com.chayiges;

import org.springframework.data.jpa.repository.JpaRepository;

import java.time.YearMonth;
import java.util.UUID;

/**
 * 学生表的jap查询
 *
 * @author chayiges
 */
public interface Students extends JpaRepository<Student, UUID> {

	/**
	 * 根据年月查询学生表
	 * @param integer convert转换后年月的整数形式
	 * @return 学生表
	 */
	List<Student> findByYearMonth(Integer integer);

}

1.4、测试:

package jp.chayiges;

import lombok.RequiredArgsConstructor;
import org.junit.jupiter.api.Test;

import java.time.YearMonth;
import java.util.UUID;
import java.util.List;


/**
 * jap查询测试
 *
 * @author chayiges
 */
@RequiredArgsConstructor
public class StudentJPAUnitTests {

	/** 实体类到数据库表的转换器 */
	final YearMonthIntegerAttributeConverterauto yearMonthIntegerAttributeConverterauto;

	/** 学生表jpa */
	final Students students;

     /**
	 * 正确的情况テスト
	 */
	@Test
	void findByYearMonthTest() {

        YearMonth yearMonth = YearMonth.of(2022, 7);
        // 创建学生对象
        Student stu = new Student(UUID.randomUUID(), "孙汐", yearMonth);
        // 调用 jpa 方法进行保存,保存的时候会进入自定义的Convert实现类中进行实体类属性值到数据                
        // 库中对应字段值的转换
        this.students.save(stu);

        // 调用 jpa 方法查询
        List<Student> studentList = this.students.findByYearMonth(yearMonth);

    }


    /**
	 * 错误的情况テスト
	 */
	@Test
	void findByYearMonthTest() {

        YearMonth yearMonth = YearMonth.of(2022, 7);
        // 创建学生对象
        Student stu = new Student(UUID.randomUUID(), "孙汐", yearMonth);
        // 调用 jpa 方法进行保存,保存的时候会进入自定义的Convert实现类中进行实体类属性值到数据                
        // 库中对应字段值的转换
        this.students.save(stu);

        // 调用 jpa 方法查询
        List<Student> studentList = this.students.findByYearMonth(this
                .yearMonthIntegerAttributeConverterauto
                    .convertToDatabaseColumn(yearmonth));

        // 抛出 InvalidDataAccessApiUsageException 异常

    }


}



版权声明:本文为m0_38137988原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。