how to force ejb3 to reload value from data base and not use those of the context - jpa

Hello here I have a big problem that I hope to find help
here I have two entities
#Entity
#Inheritance(strategy=InheritanceType.JOINED)
#DiscriminatorColumn(name="Role", discriminatorType=DiscriminatorType.STRING)
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private Long id;
#Column(name="nom",nullable=false)
private String nom;
#Column(name="Role",nullable=false, insertable=false)
private String Role ;
//...
}
#Entity
#Table(name="ResCom")
#DiscriminatorValue("ResCom")
public class ResCom extends Utilisateur {
/...
}
the first thing I do
ResCom rsCom= new ResCom(nom,prenom, email,civilite,
SysQl.crypePasse(pass));
gr.create(rsCom);
I check my database I see that property is ResCom insert
but when I check the value of role I get null
Utilisateur tets= gr.findByEmail(email);
message=tets.getEmail()+" and Role :"+tets.getRole()+"";
but in my bass it ResCom !!!!!
the problem disappears when I deploy the project again
I hope you have a solution
And thank you in advance
sorry for my English

Without seeing how you persist, load your entity, i recommend using entity manager's refresh method. Something like,
entityManager.refresh(yourEntity);

Related

Querying revisions of nested object using spring-data-envers

I'm trying to implement entity auditing in my Java Spring Boot project using spring-data-envers. All the entities are being created as they should, but I've come up against a brick wall when executing the query.
parentRepository.findRevisions(id).stream().map(Parent::getEntity).collect(Collectors.toList());
During this select the repository is supposed to fetch info also from the child entity, instead I get unable to find <child object> with {id}.
According to my experiments categoryId is being searched in the Category_Aud table, instead of the actual table with desired data.
Code snippets:
#Data
#Entity
#Audited
#NoArgsConstructor
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Enumerated(EnumType.STRING)
private Status status;
#Enumerated(EnumType.STRING)
private Type requestType;
private String fullName;
#ManyToOne
#JoinColumn(name = "child_id")
private Child child;
}
#Data
#Entity
#Audited
#NoArgsConstructor
public class Child {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
}
I've extended Parent with RevisionRepository
#Repository
public interface ParentRepository extends RevisionRepository<Parent, Long, Long>, JpaRepository<Parent, Long>
And annotated my SpringBootApplication entry class with:
#EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean.class)
I couldn't find any explanation for this so far, how can make parentRepository get what I need?
The underlying problem here is that the reference from a versioned entity isn't really properly defined. Which variant of the reference should be returned? The one at the start of the version you use as a basis, the one at the end? The one that exists right now?
There are scenarios for which each variant makes sense.
Therefor you have to query the revisions yourself and can't simply navigate to them.

Why do I get "Schema-validation: missing sequence [SEQ_BANDO]" error?

when i start my tomcat,I get this error: "Schema-validation: missing sequence [SEQ_BANDO]".
This is my entity:
#Entity
#NamedQuery(name="bando.findAll", query= "SELECT b FROM bando b")
public class Bando extends BaseBean implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name="BANDO_ID_GENERATOR", sequenceName="SEQ_BANDO", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="BANDO_ID_GENERATOR")
private Long id;
and so going on...
Is there something I'm missing?
Forgot to add important notes...I'm using postgresql and I got a bunch of other entity classes,it works fine for them

JEE, JPA facade edit many to many relation

I'm facing an issue i can't figure out.
I got 2 entities : User and Course with a Many to Many relationship
User.java
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
#ManyToMany(cascade = CascadeType.MERGE)
#JoinTable(
name="USR_COURSES",
joinColumns=#JoinColumn(name="USR_ID", referencedColumnName="ID"),
inverseJoinColumns=#JoinColumn(name="COURSE_ID",referencedColumnName="ID"))
private List<Course> courses;
...
Course.java
#Entity
#Table(uniqueConstraints=#UniqueConstraint(columnNames="CODE"))
public class Course implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String code;
private String name;
private String content;
#ManyToMany(mappedBy="courses",cascade = CascadeType.MERGE)
private List<User> users;
...
If i create a user and set him some courses, the join table will be updated with the new relations between the User and the Courses.
However if i want to edit a user by adding him courses, the join table is not update :
List<Course> test = myUser.getCourse();
test.add(facade.find(1l));
myUser.setCourse(test);
userFacade.edit(myUser);
I'm using NetBean and the AbstractFacade generated.
Thanks for helping !
In order for the cascade to work in that case you would need to set dependencies in the both sides of the ManyToMany relationship.
That means that you would need to do the following:
List<Course> test = myUser.getCourse();
Course course = facade.find(1l);
course.getUsers().add(myUser);
test.add(course);
myUser.setCourse(test);
userFacade.edit(myUser);
When you query for the Course you do not get the user list because you only have Cascade.MERGE set up on that relationship. This means that you need to set it manually as above.

The attribute [] is not present in the managed type

I'm doing an application that has this relation ship: A personal contact has an Email.
So i'm trying to find the Emails from the personal contact and I'm doing this query using Criteria but always return IllegalArgumentException:
#Override
public Email findByEmail(PersonalContact personalContact) {
CriteriaBuilder criteriaBuilder = entityManager().getCriteriaBuilder();
CriteriaQuery<Email> criteriaQuery = criteriaBuilder.createQuery(Email.class);
Root<Email> email = criteriaQuery.from(Email.class);
criteriaQuery.where(criteriaBuilder.equal(
email.get("personalContact"), criteriaBuilder.parameter(PersonalContact.class, "personalContact")));
TypedQuery<Email> typedQuery = entityManager().createQuery(criteriaQuery);
typedQuery.setParameter("personalContact", personalContact);
return typedQuery.getSingleResult();
}
Personal contact is like a foreign key.
And here is my Email class:
#Entity
#Table(name = "Email")
public class Email implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String mainEmail;
private List<String> secondaryMail;
#JoinColumn(name = "personal")
#OneToOne(fetch = FetchType.LAZY)
private PersonalContact pContact;
and here is my Personal Contact class:
#Entity
#Table(name = "PERSONALCONTACT")
public class PersonalContact extends Contact implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "PERSONAL_ID")
private Long id;
//Other variables
#OneToOne(fetch=FetchType.LAZY, mappedBy="personal")
private Email email;
And every time I execute the query this is the return:
Exception in thread "AWT-EventQueue-0"
java.lang.IllegalArgumentException: The attribute [personalContact] is
not present in the managed type [EntityTypeImpl#1230307250:Email [
javaType: class csheets.ext.crm.contact.Email descriptor:
RelationalDescriptor(csheets.ext.crm.contact.Email -->
[DatabaseTable(Email)]), mappings: 5]].
I did some search and the others programmers said the problem was on the name of the variables... but i guess the names of the variables are correct.
So what I'm doing wrong? perhaps the relationship between that two classes?
Thank you!
If you read the exception message carefully, you'll find that it is complaining that class Email does not have a property (attribute) called personalContact, and indeed, there is no such property. Presumably you meant the pContact property?
(Mistakes such as this are why I recommend querying JPA via Querydsl: code completion would likely have prevented this mistake, and even if not, you would have gotten a clear compiler message when trying to use a non-existing property)

EJB JPA QL. Need query to get data from DB by element in Collection object

I am facing a proble that put me in difficult situation.
I have class Article:
#Entity
#Table(name = "Articles")
public class Article implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="article_id")
private Long id;
#Column(name="a_name")
private String name;
#Column(name="a_content")
private String content;
#OneToMany
#Column(name="a_tag")
private Collection <Tags> tag;
#Entity
#Table(name = "Tags")
public class Tags implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="tag_id")
private Long tag_id;
#Column(name="tag_name",nullable=false)
private String tag_name;
#Column(name="tag_descr")
private String tag_descr;
//position 0 - supertag
//position 1 - subsupertag
//position 2 - subtags
//Collection limited to 3 elements.(3 tags at most, necessaryly Super,subsuper,subtag
#Column(name="super_tags")
#OneToMany
private Collection<Tags> supertags = new ArrayList<Tags>(3);
//0-supertag 1-subsupertag 2- subtags
#Column(name="tag_type")
private int tag_type;
My tagging system is such that I have Supertag, subsuprttag and subtag. Supertag is parent for subsupertag and subtag, subsupertag is parent for subtag.
Each article has super, subsuper and sub tags.
Now, I want to get only articles from database, that has a certain tag, but have no idea how to refere to , for example, element 2 in Collection tags (by name or position), (which would be subtag).
final String q = "SELECT f FROM Article f WHERE f.a_tag= ..I m lost here ...
EntityManager em;
em.createQuery(q).getResultList();
I hope my question is clear enough. I gave it my best shot)) Thank you.
You can join to the tags to access them in JPQL,
see,
http://en.wikibooks.org/wiki/Java_Persistence/JPQL#JOIN
As for the type of Tag, how is the type stored in the database?