Retrieving clean Entity from EntityManager
by chris@chrismiles.org
Good Afternoon,
I am using Hibernate behing JPA and have the following problem.
My application pulls an entity out using the find operation of the
EntityManager, and then somewhere else in my application I want to pull
the same Entity out again cleanly with the current database state rather
than the dirty version but any time I try I get the same dirty data.
I have tried to detach the dirty version and then fetch the Entity again
but it is still same.
I have also tried the CacheRetrieveMode.BYPASS hint on the fetch in case
it is a caching problem.
How can I fetch a clean instance of my Entity side by side with the dirty
version?
Thanks
Chris
14 years
GlassFish, JSR-303, Custom Annotation does not fire
by Roger Varley
Hi
I'm just starting JEE6 with Glassfish and JSF, and I'm trying to create
my first JSR-303 validation. The problem I've got is that despite the
fact that everything compiles, the validator class is never called. I've
listed the code below. (I know that the validator doesn't make logical
sense at the moment, there's more to go in it, I'm just trying to get it
to work at the moment.) Can anyone see what I'm doing wrong.
Regards
The annotation;
package com.vasilikon.pembridge.validators;
import com.vasilikon.pembridge.entities.TelephoneType;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target({FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = PhoneNumberValidator.class)
@Documented
public @interface PhoneNumberCheck
{
String message() default "Invalid Telephone number.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
TelephoneType value();
}
The validator;
package com.vasilikon.pembridge.validators;
import com.vasilikon.pembridge.entities.TelephoneType;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class PhoneNumberValidator implements
ConstraintValidator<PhoneNumberCheck, Object>
{
private TelephoneType type;
@Override
public void initialize(PhoneNumberCheck constraintAnnotation) {
this.type = constraintAnnotation.value();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext
context) {
try {
System.out.println("isValid called"); // Never gets
here
long telephoneNumber = ((Long) value).longValue();
if (type == TelephoneType.MOBILE) {
return
isValidMobileNumber(context,telephoneNumber,type);
} else {
return
isValidLandLineNumber(context,telephoneNumber,type);
}
} catch (Exception e) {
/* Do Nothing */
}
return true;
}
private boolean isValidMobileNumber(ConstraintValidatorContext
context, long telephoneNumber, TelephoneType type) {
/*
* Mobile number is exactly 8 digits long
* and starts 99nnnnnn
*/
boolean valid = ((telephoneNumber > 99000000)
&& (telephoneNumber < 999999999));
if (!valid) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("A mobile
number must be 8 digits starting with 99")
.addNode(String.valueOf(telephoneNumber))
.addConstraintViolation();
}
return valid;
}
private boolean isValidLandLineNumber(ConstraintValidatorContext
context, long telephoneNumber, TelephoneType type) {
throw new UnsupportedOperationException("Not yet
implemented");
}
}
and my backing bean (trimmed);
@Named
@RequestScoped
public class PhoneNumberPromptBean {
@Inject
PembridgeServices services;
@NotNull(message="You must select a number type")
private TelephoneType type;
@PhoneNumberCheck(TelephoneType.MOBILE)
private long telephoneNumber;
<Getters and Setters>
14 years
Subquery issue
by Haswell, Joe
Hello everyone,
I'm having a bit of an issue with executing a subquery. I need to find all of the items whose IDs are not in a particular set. If I obtain the set before-hand by executing the query that retrieves the set, then it works; if I try to execute the query that retrieves the set as a subquery, then it doesn't work (SQLException, column not found).
For example:
userGroupMappingsWithoutDefaultRoles =
DetachedCriteria.forClass(UserToSecurityGroup.class)
.createAlias(
"role",
"securityRole"
).add(
Restrictions.not(
Restrictions.in(
"securityRole.key",
RoleLoader.DEFAULT_ROLE_KEYS
)
)
).setProjection(
Projections.property("userGroup.id")
);
DetachedCriteria crit =
DetachedCriteria.forClass(UserGroupMember.class)
.createAlias(
"userGroup",
"uGroup"
)
.add(
Subqueries.propertyIn(
"uGroup.id",
userGroupMappingsWithoutDefaultRoles
)
);
Fails
However:
List<PersistenceID> userGroupIds =
userGroupMappingsWithoutDefaultRoles
.getExecutableCriteria(
context.getSession()
).list();
DetachedCriteria crit =
DetachedCriteria.forClass(UserGroupMember.class)
.createAlias(
"userGroup",
"uGroup"
)
.add(
Property.forName("uGroup.id").in(userGroupIds)
);
Works. There's gotta be something simple that I'm doing wrong here. Any help would be appreciated!
Joe H.
14 years
Hibernate JPA leaves inactive sessions opened in Oracle
by Oscar
Hi to all, this is my first post. I'm working in a project using Struts
2.1.8 and Hibernate JPA . My application works fine, i'm using c3po also.
The problem is after a while because it seems that hibernate leaves a lot of
open sessions in the database (Oracle 9i) that are inactive, so suddenly i'm
navigating in the application and it appears the exception
IllegalStateException: Session is closed! or EntityManager is closed and it
looks like it can't get an active connection because there are so many open
sessions in the database, so the only way to solve the situation is to
restart database server or kill the inactive sessions in Oracle.
I'm not using anything special where i initialize EntityManagerFactory or
EntityManager as you can see:
EntityManager entityManager;
EntityManagerFactory factory;
if (factory == null || !factory.isOpen()) {
factory =
Persistence.createEntityManagerFactory("GTBancaPU");
}
entityManager = factory.createEntityManager();
try {
if(!entityManager.isOpen()) {
factory =
Persistence.createEntityManagerFactory("GTBancaPU");
entityManager = factory.createEntityManager();
}
entityManager.createQuery("FROM
WbkTiposTransaccion").getResultList();
} catch(Exception ex) {
factory =
Persistence.createEntityManagerFactory("GTBancaPU");
entityManager = factory.createEntityManager();
}
((BaseAction)invokedAction.getAction()).setEntityMngr(entityManager);
transaction = entityManager.getTransaction();
So i initialize EntityManagerFactory just once in my entire application and
EntityManager is initialized on each request (at the beginning) and closed
at the end of the request with the next code:
if (isBaseAction && transaction.isActive()) {
entityManager.getTransaction().commit();
}
if (entityManager != null && entityManager.isOpen()) {
entityManager.close();
}
Do you know why hibernate leaves open sessions in my database? Also when i
query the database to see the query that inactive sessions executed i get
that:
select a.sid, a.serial#, b.sql_text from v$session a, v$sqlarea b
where a.sql_address=b.address and a.MACHINE IN( 'MyMachine' );
10 1229 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS WHERE PARAMETER
='NLS_DATE_FORMAT'
13 601 SELECT VALUE FROM NLS_INSTANCE_PARAMETERS WHERE PARAMETER
='NLS_DATE_FORMAT'
Hibernate queries NLS_INSTANCE_PARAMETERS and the result of that query is
null.
Regards.
--
Oscar Calderón
SCJP 6 <http://javahowto.net>
14 years