use of jakarta.persistence.Id in project hibernate-orm by hibernate.
the class JpaStreamTest method runTerminalOperationTests.
private void runTerminalOperationTests(Runnable prepare, List<Runnable> onCloseCallbacks, Runnable onCloseAssertion, boolean flatMapBefore, boolean flatMapAfter, SessionFactoryScope scope) {
// collect as list
scope.inTransaction(session -> {
Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
ResourceRegistry resourceRegistry = resourceRegistry(session);
try {
List<MyEntity> entities = stream.collect(Collectors.toList());
assertTrue(resourceRegistry.hasRegisteredResources());
assertEquals(10, entities.size());
} finally {
stream.close();
assertFalse(resourceRegistry.hasRegisteredResources());
}
onCloseAssertion.run();
});
// forEach (TestCase based on attachment EntityManagerIllustrationTest.java in HHH-14449)
scope.inTransaction(session -> {
Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
ResourceRegistry resourceRegistry = resourceRegistry(session);
try {
AtomicInteger count = new AtomicInteger();
stream.forEach(myEntity -> count.incrementAndGet());
assertTrue(resourceRegistry.hasRegisteredResources());
assertEquals(10, count.get());
} finally {
stream.close();
assertFalse(resourceRegistry.hasRegisteredResources());
}
onCloseAssertion.run();
});
// filter (always true) + forEach (TestCase based on attachment EntityManagerIllustrationTest.java in HHH-14449)
scope.inTransaction(session -> {
Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
ResourceRegistry resourceRegistry = resourceRegistry(session);
try {
AtomicInteger count = new AtomicInteger();
stream.filter(Objects::nonNull).forEach(myEntity -> count.incrementAndGet());
assertTrue(resourceRegistry.hasRegisteredResources());
assertEquals(10, count.get());
} finally {
stream.close();
assertFalse(resourceRegistry.hasRegisteredResources());
}
onCloseAssertion.run();
});
// filter (partially true) + forEach (TestCase based on attachment EntityManagerIllustrationTest.java in HHH-14449)
scope.inTransaction(session -> {
Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
ResourceRegistry resourceRegistry = resourceRegistry(session);
try {
AtomicInteger count = new AtomicInteger();
stream.filter(entity -> entity.getId() % 2 == 0).forEach(myEntity -> count.incrementAndGet());
assertTrue(resourceRegistry.hasRegisteredResources());
assertEquals(5, count.get());
} finally {
stream.close();
assertFalse(resourceRegistry.hasRegisteredResources());
}
onCloseAssertion.run();
});
// multiple chained operations (TestCase based on attachment EntityManagerIllustrationTest.java in HHH-14449)
scope.inTransaction(session -> {
Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
ResourceRegistry resourceRegistry = resourceRegistry(session);
try {
AtomicInteger count = new AtomicInteger();
stream.filter(Objects::nonNull).map(Optional::of).filter(Optional::isPresent).map(Optional::get).forEach(myEntity -> count.incrementAndGet());
assertTrue(resourceRegistry.hasRegisteredResources());
assertEquals(10, count.get());
} finally {
stream.close();
assertFalse(resourceRegistry.hasRegisteredResources());
}
onCloseAssertion.run();
});
// mapToInt
scope.inTransaction(session -> {
Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
ResourceRegistry resourceRegistry = resourceRegistry(session);
try {
int sum = stream.mapToInt(MyEntity::getId).sum();
assertTrue(resourceRegistry.hasRegisteredResources());
assertEquals(55, sum);
} finally {
stream.close();
assertFalse(resourceRegistry.hasRegisteredResources());
}
onCloseAssertion.run();
});
// mapToLong
scope.inTransaction(session -> {
Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
ResourceRegistry resourceRegistry = resourceRegistry(session);
try {
long result = stream.mapToLong(entity -> entity.id * 10).min().getAsLong();
assertTrue(resourceRegistry.hasRegisteredResources());
assertEquals(10, result);
} finally {
stream.close();
assertFalse(resourceRegistry.hasRegisteredResources());
}
onCloseAssertion.run();
});
// mapToDouble
scope.inTransaction(session -> {
Stream<MyEntity> stream = getMyEntityStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter);
ResourceRegistry resourceRegistry = resourceRegistry(session);
try {
double result = stream.mapToDouble(entity -> entity.id * 0.1D).max().getAsDouble();
assertTrue(resourceRegistry.hasRegisteredResources());
assertEquals(1, result, 0.1);
} finally {
stream.close();
assertFalse(resourceRegistry.hasRegisteredResources());
}
onCloseAssertion.run();
});
// Test call close explicitly
scope.inTransaction(session -> {
try (Stream<Long> stream = getLongStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter)) {
ResourceRegistry resourceRegistry = resourceRegistry(session);
try {
Object[] result = stream.sorted().skip(5).limit(5).toArray();
assertTrue(resourceRegistry.hasRegisteredResources());
assertEquals(5, result.length);
assertEquals(6, result[0]);
assertEquals(10, result[4]);
} finally {
stream.close();
assertFalse(resourceRegistry.hasRegisteredResources());
}
onCloseAssertion.run();
}
});
// Test Java 9 Stream methods
scope.inTransaction(session -> {
Method takeWhileMethod = ReflectHelper.getMethod(Stream.class, "takeWhile", Predicate.class);
if (takeWhileMethod != null) {
try (Stream<Long> stream = getLongStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter)) {
ResourceRegistry resourceRegistry = resourceRegistry(session);
try {
Predicate<Integer> predicate = id -> id <= 5;
Stream<Integer> takeWhileStream = (Stream<Integer>) takeWhileMethod.invoke(stream, predicate);
List<Integer> result = takeWhileStream.collect(Collectors.toList());
assertTrue(resourceRegistry.hasRegisteredResources());
assertEquals(5, result.size());
assertTrue(result.contains(1));
assertTrue(result.contains(3));
assertTrue(result.contains(5));
} finally {
stream.close();
assertFalse(resourceRegistry.hasRegisteredResources());
}
onCloseAssertion.run();
} catch (IllegalAccessException | InvocationTargetException e) {
fail("Could not execute takeWhile because of " + e.getMessage());
}
}
});
scope.inTransaction(session -> {
Method dropWhileMethod = ReflectHelper.getMethod(Stream.class, "dropWhile", Predicate.class);
if (dropWhileMethod != null) {
try (Stream<Long> stream = getLongStream(prepare, session, onCloseCallbacks, flatMapBefore, flatMapAfter)) {
ResourceRegistry resourceRegistry = resourceRegistry(session);
Predicate<Integer> predicate = id -> id <= 5;
Stream<Integer> dropWhileStream = (Stream<Integer>) dropWhileMethod.invoke(stream, predicate);
try {
List<Integer> result = dropWhileStream.collect(Collectors.toList());
assertTrue(resourceRegistry.hasRegisteredResources());
assertEquals(5, result.size());
assertTrue(result.contains(6));
assertTrue(result.contains(8));
assertTrue(result.contains(10));
} finally {
stream.close();
assertFalse(resourceRegistry.hasRegisteredResources());
}
onCloseAssertion.run();
} catch (IllegalAccessException | InvocationTargetException e) {
fail("Could not execute takeWhile because of " + e.getMessage());
}
}
});
}
use of jakarta.persistence.Id in project hibernate-orm by hibernate.
the class AnnotationBinder method addProperty.
private static int addProperty(PropertyContainer propertyContainer, XProperty property, List<PropertyData> inFlightPropertyDataList, MetadataBuildingContext context) {
// and if so, skip it..
for (PropertyData propertyData : inFlightPropertyDataList) {
if (propertyData.getPropertyName().equals(property.getName())) {
Id incomingIdProperty = property.getAnnotation(Id.class);
Id existingIdProperty = propertyData.getProperty().getAnnotation(Id.class);
if (incomingIdProperty != null && existingIdProperty == null) {
throw new MappingException(String.format("You cannot override the [%s] non-identifier property from the [%s] base class or @MappedSuperclass and make it an identifier in the [%s] subclass!", propertyData.getProperty().getName(), propertyData.getProperty().getDeclaringClass().getName(), property.getDeclaringClass().getName()));
}
// EARLY EXIT!!!
return 0;
}
}
final XClass declaringClass = propertyContainer.getDeclaringClass();
final XClass entity = propertyContainer.getEntityAtStake();
int idPropertyCounter = 0;
PropertyData propertyAnnotatedElement = new PropertyInferredData(declaringClass, property, propertyContainer.getClassLevelAccessType().getType(), context.getBootstrapContext().getReflectionManager());
/*
* put element annotated by @Id in front
* since it has to be parsed before any association by Hibernate
*/
final XAnnotatedElement element = propertyAnnotatedElement.getProperty();
if (hasIdAnnotation(element)) {
inFlightPropertyDataList.add(0, propertyAnnotatedElement);
/*
* The property must be put in hibernate.properties as it's a system wide property. Fixable?
* TODO support true/false/default on the property instead of present / not present
* TODO is @Column mandatory?
* TODO add method support
*/
if (context.getBuildingOptions().isSpecjProprietarySyntaxEnabled()) {
if (element.isAnnotationPresent(Id.class) && element.isAnnotationPresent(Column.class)) {
String columnName = element.getAnnotation(Column.class).name();
for (XProperty prop : declaringClass.getDeclaredProperties(AccessType.FIELD.getType())) {
if (!prop.isAnnotationPresent(MapsId.class)) {
/*
* The detection of a configured individual JoinColumn differs between Annotation
* and XML configuration processing.
*/
boolean isRequiredAnnotationPresent = false;
JoinColumns groupAnnotation = prop.getAnnotation(JoinColumns.class);
if ((prop.isAnnotationPresent(JoinColumn.class) && prop.getAnnotation(JoinColumn.class).name().equals(columnName))) {
isRequiredAnnotationPresent = true;
} else if (prop.isAnnotationPresent(JoinColumns.class)) {
for (JoinColumn columnAnnotation : groupAnnotation.value()) {
if (columnName.equals(columnAnnotation.name())) {
isRequiredAnnotationPresent = true;
break;
}
}
}
if (isRequiredAnnotationPresent) {
// create a PropertyData for the specJ property holding the mapping
PropertyData specJPropertyData = new PropertyInferredData(declaringClass, // same dec
prop, // the actual @XToOne property
propertyContainer.getClassLevelAccessType().getType(), // TODO we should get the right accessor but the same as id would do
context.getBootstrapContext().getReflectionManager());
context.getMetadataCollector().addPropertyAnnotatedWithMapsIdSpecj(entity, specJPropertyData, element.toString());
}
}
}
}
}
if (hasToOneAnnotation(element)) {
context.getMetadataCollector().addToOneAndIdProperty(entity, propertyAnnotatedElement);
}
idPropertyCounter++;
} else {
inFlightPropertyDataList.add(propertyAnnotatedElement);
}
if (element.isAnnotationPresent(MapsId.class)) {
context.getMetadataCollector().addPropertyAnnotatedWithMapsId(entity, propertyAnnotatedElement);
}
return idPropertyCounter;
}
use of jakarta.persistence.Id in project hibernate-orm by hibernate.
the class DefaultCatalogAndSchemaTest method verifyEntityPersisterQualifiers.
private void verifyEntityPersisterQualifiers(Class<?> entityClass, ExpectedQualifier expectedQualifier) {
// The hbm.xml mapping unfortunately sets the native entity name on top of the JPA entity name,
// so many methods that allow retrieving the entity persister or entity metamodel from the entity class no longer work,
// because these methods generally assume the native entity name is the FQCN.
// Thus we use custom code.
AbstractEntityPersister persister = (AbstractEntityPersister) sessionFactory.getRuntimeMetamodels().getMappingMetamodel().streamEntityDescriptors().filter(p -> p.getMappedClass().equals(entityClass)).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find persister for " + entityClass));
String jpaEntityName = sessionFactory.getRuntimeMetamodels().getJpaMetamodel().getEntities().stream().filter(p -> p.getBindableJavaType().equals(entityClass)).findFirst().orElseThrow(() -> new IllegalStateException("Cannot find entity metamodel for " + entityClass)).getName();
// Table names are what's used for Query, in particular.
verifyOnlyQualifier(persister.getTableName(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
// Here, to simplify assertions, we assume all derived entity types have:
// - an entity name prefixed with the name of their super entity type
// - the same explicit catalog and schema, if any, as their super entity type
verifyOnlyQualifier(persister.getTableNames(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
// This will include SQL generated by ID generators in some cases, which will be validated here
// because ID generators table/sequence names are prefixed with the owning entity name.
verifyOnlyQualifier(persister.getSQLInsertStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
if (persister.isIdentifierAssignedByInsert()) {
verifyOnlyQualifier(persister.getSQLIdentityInsertString(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
}
try {
verifyOnlyQualifierOptional(persister.getIdentitySelectString(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
} catch (MappingException e) {
if (e.getMessage().contains("does not support identity key generation")) {
// For some reason Oracle12cIdentityColumnSupport#supportsInsertSelectIdentity() returns true,
// but getIdentitySelectString is not implemented, resulting in runtime exceptions.
// Whatever, we'll just ignore this for now.
} else {
throw e;
}
}
verifyOnlyQualifier(persister.getSQLUpdateStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
verifyOnlyQualifier(persister.getSQLLazyUpdateStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
verifyOnlyQualifier(persister.getSQLDeleteStrings(), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
// This is used in the "select" id generator in particular.
verifyOnlyQualifierOptional(persister.getSelectByUniqueKeyString("basic"), SqlType.RUNTIME, jpaEntityName, expectedQualifier);
}
use of jakarta.persistence.Id in project hibernate-orm by hibernate.
the class StatelessDoWorkTest method testDoReturningWork.
@Test
public void testDoReturningWork(SessionFactoryScope scope) {
String retrievedEntityName;
try (StatelessSession statelessSession = scope.getSessionFactory().openStatelessSession()) {
retrievedEntityName = statelessSession.doReturningWork((connection) -> {
try (PreparedStatement preparedStatement = connection.prepareStatement("SELECT NAME FROM TEST_ENTITY WHERE ID = ?")) {
preparedStatement.setInt(1, PERSISTED_TEST_ENTITY_ID);
ResultSet resultSet = preparedStatement.executeQuery();
String name = null;
if (resultSet.next()) {
name = resultSet.getString(1);
}
return name;
}
});
}
assertThat(retrievedEntityName, is(EXPECTED_ENTITY_NAME));
}
use of jakarta.persistence.Id in project boot by workoss.
the class JakartaEntityClassFinder method findTableColumnInfo.
@Override
public Optional<ClassTableColumnInfo> findTableColumnInfo(ProviderContext context) {
return findTableColumnInfo(context, field -> !field.isAnnotationPresent(Transient.class), (tableColumnInfo, field) -> {
String columnName = ObjectUtil.underscoreName(field.getName());
Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof Column) {
// 自定义列名称
Column column = (Column) annotation;
if (!ObjectUtil.isBlank(column.name())) {
columnName = column.name();
}
}
if (annotation instanceof Id) {
tableColumnInfo.idColumn(new ClassColumnInfo(field.getType(), field.getName(), columnName));
}
}
if (tableColumnInfo.getIdColumn() == null && "id".equalsIgnoreCase(field.getName())) {
tableColumnInfo.idColumn(new ClassColumnInfo(field.getType(), field.getName(), columnName));
}
tableColumnInfo.addColumnInfo(new ClassColumnInfo(field.getType(), field.getName(), columnName));
});
}
Aggregations