Почему Hibernate дважды вызывает запрос SQL в пользовательском классе?
Пытался создать пользовательский класс, чтобы я мог вручную вставить первичный ключ (ранее использовался @GeneratedValue (стратегии = GenerationType.IDENTITY)), но из этого поста мне кажется, что пользовательский класс - это путь вперед для ручных вставок Как создать пользовательский идентификатор с помощью hibernate, в то время как он должен быть первичным ключом таблицы
Пользовательский класс
public final class GenerateIdentity implements IdentifierGenerator {
//for some reason this is never called
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
try {
Connection connection = session.connection();
PreparedStatement ps = connection.prepareStatement("SELECT MAX(id) AS id FROM fruit.apples");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
long id = rs.getInt("id");
System.out.print("----------ID is "+id);
return id <= 0 ? 1 : id + 1;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
try {
//this part is called twice
Connection connection = session.connection();
PreparedStatement ps = connection.prepareStatement("SELECT MAX(id) AS id FROM fruits.apple");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
long id = rs.getInt("id");
return id <= 0 ? 1 : id+1;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
Сущность класса
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@EqualsAndHashCode(callSuper=false)
@Table(name = "apples", schema = "fruit")
public class MissionNode extends AuditModel {
private static final long serialVersionUID = 1L;
@JsonIgnore
@Id
/*
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id", insertable=true, updatable=true, unique=true, nullable=false)
*/
@GenericGenerator(name = "test_sequence", strategy = "{packagename}.GenerateIdentity")
@GeneratedValue(generator = "test_sequence")
@Basic(optional = false)
@Column(name = "id", nullable = false)
private Long id;
/*getters and setters*/
}