My Organization entity
#Entity
public class Organization implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
private String name;
private String type;
private byte image;
#OneToMany(cascade=CascadeType.MERGE)
#JoinColumn(name="ORGANIZATION_ID")
private List<User> admin;
My User entity
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
private String score;
private boolean online;
private String resume;
public Status status;
public enum Status {
ACTIVE, INACTIVE, VERIFIED, NOT_VERIFIED , BANNED
};
#ManyToOne(cascade=CascadeType.MERGE)
#JoinColumn(name="ORGANIZATION_ID")
private Organization organization;
#Persistent
private User_personal user_p;
public User_personal getUser_personal(){
return user_p;
}
public void setUser_personal(User_personal user_p) {
this.user_p = user_p;
}
#OneToMany(mappedBy = "user", cascade=CascadeType.MERGE)
private List<Project> projects;
I got the one-Many relation between User and Projects correctly but not working for User and Organization(many-one).I am getting error like this
WARNING: /OrganizationServlet
javax.persistence.PersistenceException: Detected attempt to establish
Organization(no-id-yet) as the parent of User(4793870697103360) but the
entity identified by User(4793870697103360) has already been persisted
without a parent. A parent cannot be established or changed once an object
has been persisted.at...
showing error at em.getTransaction().commit();.
My servlet is
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
HashMap<String,String> map = Request_to_map.getBody(request);
boolean validToken = JWT.parseJWT(request.getHeader("Access-token")
,map.get("email"));
JsonObject output = new JsonObject();
List<User> organization_admin = new ArrayList<User>();
if(validToken == true){
EntityManager em;
em = EMF.get().createEntityManager();
String organizationName = map.get("name");
String type = map.get("type");
byte image = 0;
if(map.get("image")!=null)
{
image = Byte.valueOf(map.get("image"));
}
String email = map.get("email");
if(organizationName==null||type==null||email==null||map.get("image")==null)
{
throw new IllegalArgumentException("please fill required
details");
}
try{
em.getTransaction().begin();
User user = User.find(email, em);
if(user!=null)
{
Organization.org_status status= org_status.ACTIVE;
Organization organization = new
Organization(organizationName, type,image,status);
user.setOrganization(organization);
organization_admin = organization.getAdmin();
if(organization_admin == null)
{
organization_admin = new ArrayList<User>();
}
organization_admin .add(user);
organization.setAdmin(organization_admin);
em.persist(organization);
em.persist(user);
output.addProperty("message", "done");
em.getTransaction().commit();
}
else
output.addProperty("message","No such User found.Please
check details provided");
}
finally{
if(em.getTransaction().isActive())
em.getTransaction().rollback();
// em.close();
}
}
else
output.addProperty(Constants.MESSAGE,
Constants.TokenNotAuthenticated);
response.setContentType("application/Json");
response.getWriter().println(output);
}
Can anyone help me in getting this? When user is created I am getting ORGANIZATION_ID as a column but cant create entity of organization.I dont think joins are to be used as GAE doesn't allow it.
Related
I have a Java User class, a user can have friends (List<User>). By default, Hibernate create two tables : USER and USER_FRIENDS(USER_ID,FRIENDS_ID)
The problem is when I change friends in my code and that I save(user), spring add the new friends but don't remove in the database the friends removed from the array list.
#Entitypublic class User implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String pseudo;
private String password;
private String email;
private Gender gender;
#Lob
private byte[] avatar;
private String description;
private Date birthdate;
#ManyToMany(cascade = CascadeType.ALL)
private List<Game> favoriteGames = new ArrayList<>();
#OneToMany( cascade = CascadeType.ALL)
private List<User> friends = new ArrayList<>();
I tried #ManyToMany, #OneToMany, cascade = CascadeType.ALL
Basically, first I would advise that you take special care with your equals and hashCode implementation in your entities. You did not show us that, but it should be something like this in your User.java:
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
User other = (User) o;
return id != null && id.equals(other.getId());
}
#Override
public int hashCode() {
return getClass().hashCode();
}
Those are very important, especially when working with entities in collections.
Secondly, a connection between a User and his Friends (other Users) should be modeled as Many-to-Many, because:
every user can be a friend to MANY of other users
every user can have any number of friends, in other words MANY friends
And I would model this connection like this:
#ManyToMany
#JoinTable(name = "user_friends", joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "friend_user_id"))
private Set<User> friends = new HashSet<>();
I have added Hibernate filters on my entities . These filters are applied on queries which fetch Collection of entity but not applied on queries which fetch single entity. Below is my code.
AOrganization.java
#MappedSuperclass
#FilterDef(name = "OrgFilter", parameters = { #ParamDef(name = "allowedOrgIdList", type = "long") })
#Filter(name = "OrgFilter", condition = "org_id in (:allowedOrgIdList)")
public class AOrganization implements Serializable {
#ManyToOne()
#JoinColumn(name = "org_id", nullable = true)
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
}
Site.java
#Data
#Entity
#Table(name = "site")
public class Site extends AOrganization{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "site_name")
private String siteName;
#Override
public String toString() {
return "Site [id=" + id + ", siteName=" + siteName + "]";
}
}
SiteService.java
public interface SiteService {
public List<Site> getAllSites();
public List<Site> getSiteBySiteName(String siteName);
public Site updateSiteName(Long id, String siteName);
}
SiteRepository.java
#Repository
public interface SiteRepository extends AOrganizationRepository<Site, Long> {
public List<Site> findBySiteName(String siteName);
public List<Site> findByOrganization_Id(Long orgId);
}
AOrganizationRepository.java
#NoRepositoryBean
public interface AOrganizationRepository<T, ID extends java.io.Serializable> extends CrudRepository<T, ID> {
}
SiteServiceImpl.java
#Service
public class SiteServiceImpl implements SiteService {
#Autowired
private EntityManager entityManager;
#Autowired
private SiteRepository siteRepository;
#Override
public List<Site> getAllSites() {
Iterable<Site> sites = siteRepository.findAll();
List<Site> allSites = new ArrayList<>();
sites.forEach(allSites::add);
return allSites;
}
#Override
public List<Site> getSiteBySiteName(String siteName) {
List<Site> allSites = siteRepository.findBySiteName(siteName);
return allSites;
}
#Override
public Site updateSiteName(Long id,String siteName) {
Site site = siteRepository.findById(id).get();
if(site == null)
return null;
site.setSiteName(siteName);
siteRepository.save(site);
return site;
}
}
AOrganizationAspect.java
#Aspect
#Component
#Slf4j
public class AOrganizationAspect {
#PersistenceContext
private EntityManager entityManager;
#Pointcut("execution(public * com.harshal.springboot.springfilter.repository.AOrganizationRepository+.*(..))")
protected void aOrganizationRepositoryRepositoryMethod() {
log.info("aOrganizationRepositoryRepositoryMethod");
}
#Around(value = "aOrganizationRepositoryRepositoryMethod()")
public Object enableOwnerFilter(ProceedingJoinPoint joinPoint) throws Throwable {
// Variable holding the session
Session session = null;
try {
// Get the Session from the entityManager in current persistence context
session = entityManager.unwrap(Session.class);
// Enable the filter
Filter filter = session.enableFilter("OrgFilter");
// Set the parameter from the session
List<Long> orgList = getAllowedOrgIdList();
filter.setParameterList("allowedOrgIdList", orgList);
} catch (Exception ex) {
// Log the error
log.error("Error enabling OrgFilter : Reason -" + ex.getMessage());
}
// Proceed with the joint point
Object obj = joinPoint.proceed();
// If session was available
if (session != null) {
// Disable the filter
session.disableFilter("OrgFilter");
}
// Return
return obj;
}
private List<Long> getAllowedOrgIdList() {
return Arrays.asList(2l);
}
}
So , hibernate filters are applied if method getSiteBySiteName is called and filters are not applied if findById method is called.
Below are queries :
For getSiteBySiteName :
select site0_.id as id1_2_, site0_.org_id as org_id3_2_,
site0_.site_name as site_nam2_2_ from site site0_ where site0_.org_id
in (?) and site0_.site_name=?
Please help . Thanks in advance.
For findById
select site0_.id as id1_2_0_, site0_.org_id as org_id3_2_0_,
site0_.site_name as site_nam2_2_0_, organizati1_.id as id1_1_1_,
organizati1_.address as address2_1_1_, organizati1_.org_name as
org_name3_1_1_ from site site0_ left outer join organization
organizati1_ on site0_.org_id=organizati1_.id where site0_.id=?
findById is using the EntityManager.find method and do not create a query.
Plus Hibernate Filters only work on queries.
You should write a query instead of using findById
I am new to Spring Data JPA and CRUD repositories. I have code that can save to the database if I save each individual entity, but thought that I should be able to save the parent entity and have the contained child entities automatically get saved or updated. Am I doing something wrong?
The code that executes the save:
private static CustomerRepository customerRepository;
#Transactional
public ResultCreateCustomer addCustomer(NameTable nameIn, Address addressIn)
throws Exception {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
customerRepository = context.getBean(CustomerRepository.class);
ResultCreateCustomer result = new ResultCreateCustomer(0, 0, 0, DATABASE_OR_SYSTEM_ERROR);
try {
NameTable theName = new NameTable();
theName.setFirstName(nameIn.getFirstName());
theName.setLastName(nameIn.getLastName());
Address theAddress = new Address();
theAddress.setStreetNo(addressIn.getStreetNo());
theAddress.setStreetName(addressIn.getStreetName());
theAddress.setCityStateZip(addressIn.getCityStateZip());
Customer theCustomer = new Customer();
theCustomer.setNameTable(theName);
theCustomer.setAddress(theAddress);
customerRepository.save(theCustomer);
} catch (Exception e) {
this.log.error("got exception: " + e.getClass() + ": " + e.getMessage());
}
context.close();
return result;
}
The code for the Customer entity:
#Entity
#org.hibernate.annotations.Proxy(lazy=false)
#Table(name="Customer")
public class Customer implements Serializable {
public Customer() {
}
#Column(name="ID", nullable=false, unique=true)
#Id
#GeneratedValue(generator="COM_COMPORIUM_CUSTOMER_DOMAIN_CUSTOMER_ID_GENERATOR")
#org.hibernate.annotations.GenericGenerator(name="COM_COMPORIUM_CUSTOMER_DOMAIN_CUSTOMER_ID_GENERATOR", strategy="native")
private int ID;
#ManyToOne(targetEntity=com.comporium.customer.addresses.Address.class, fetch=FetchType.LAZY)
#org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.LOCK})
#JoinColumns({ #JoinColumn(name="AddressID", referencedColumnName="ID") })
private com.comporium.customer.addresses.Address address;
#OneToOne(targetEntity=com.comporium.customer.contactrolodex.NameTable.class, fetch=FetchType.LAZY)
#org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK})
#JoinColumns({ #JoinColumn(name="NameTableID", nullable=false) })
private com.comporium.customer.contactrolodex.NameTable nameTable;
#Column(name="IndustryCode", nullable=false)
private int industryCode;
#Column(name="DemographicCode", nullable=false)
private int demographicCode;
#Column(name="Ranking", nullable=false)
private int ranking;
public void setNameTable(com.comporium.customer.contactrolodex.NameTable value) {
this.nameTable = value;
}
public com.comporium.customer.contactrolodex.NameTable getNameTable() {
return nameTable;
}
// Other setters and getters follow
}
The code for the first child class:
#Entity
#org.hibernate.annotations.Proxy(lazy=false)
#Table(name="NameTable")
public class NameTable implements Serializable {
public NameTable() {
}
#Column(name="ID", nullable=false, unique=true)
#Id
#GeneratedValue(generator="COM_COMPORIUM_CUSTOMER_CONTACTROLODEX_NAMETABLE_ID_GENERATOR")
#org.hibernate.annotations.GenericGenerator(name="COM_COMPORIUM_CUSTOMER_CONTACTROLODEX_NAMETABLE_ID_GENERATOR", strategy="native")
private int ID;
#Column(name="FirstName", nullable=true, length=30)
private String firstName;
#Column(name="LastName", nullable=true, length=40)
private String lastName;
#OneToOne(mappedBy="nameTable", targetEntity=com.comporium.customer.domain.Customer.class, fetch=FetchType.LAZY)
#org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.LOCK})
private com.comporium.customer.domain.Customer customer;
}
The repository interface, CustomerRepository:
package com.comporium.customer.repositories;
import org.springframework.data.repository.CrudRepository;
import com.comporium.customer.domain.Customer;
public interface CustomerRepository extends CrudRepository<Customer, Integer> {
}
When I run the executable (via a SOAP call), I get an exception:
2014-11-19 09:57:59,253 ERROR VPcodeDao:306 - got exception: class org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation: com.comporium.customer.domain.Customer.nameTable -> com.comporium.customer.contactrolodex.NameTable; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation: com.comporium.customer.domain.Customer.nameTable -> com.comporium.customer.contactrolodex.NameTable
Is there a way for the save(theCustomer) to save the contained child entities also?
not sure if you ever get a solution for this. but the solution is to define cascading
#OneToOne(cascade = {CascadeType.ALL}, mappedBy="nameTable", targetEntity=com.comporium.customer.domain.Customer.class, fetch=FetchType.LAZY)
I have just started with App Engine and I have tried to make a very simple app which adds Person objects with distinctive names to the datastore. This the object:
#PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Person {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
#Persistent
#Unique
private String name;
public Person(String nameIn){
this.name = nameIn;
}
public Long getId(){
return this.id;
}
public void setId(Long idIn){
this.id = idIn;
}
}
This servlet is responsible for persisting objects on datastore. But prior to that, the method doesUserExist(String) checks whether object with the same 'name' field exists:
#SuppressWarnings("serial")
public class PersonDatastoreServlet extends HttpServlet {
private static final String PARAM_NAME = "name";
private PersistenceManager pmf = PMF.get().getPersistenceManager();
public void doGet(HttpServletRequest req, HttpServletResponse response)
throws IOException {
String name = req.getParameter(PARAM_NAME);
PrintWriter printWriter = response.getWriter();
try{
if(!doesUserExist(name)) {
Person p = new Person(name);
pmf.makePersistent(p);
response.setContentType("text/html");
printWriter.println("<h1>"+p.getId()+"</h1>");
}
else {
response.setContentType("text/html");
printWriter.println("<p>User already exists</p>");
}
}
catch(Exception e) {
throw new IOException();
}
finally{
pmf.close();
}
}
private boolean doesUserExist(String nameIn) {
Query q = pmf.newQuery(Person.class);
q.setFilter("name == lastNameParam");
q.declareParameters("String lastNameParam");
String name = nameIn;
try{
List<Person> list = (List<Person>) q.execute(name);
if (list.isEmpty()){
return false;
}
else return true;
}
finally{
q.closeAll();
}
}
}
The take seems very straightforward, but it just not working. I have a form which processing the request. When I run my app for the first time it does successfully create and persist an object, however whenever i want to add another object with a different name, I am getting the Error
Error: Server Error
The server encountered an error and could not complete your request.
If the problem persists, please report your problem and mention this error message and the query that caused it.
It indicates that the query causes the problem but I have idea what is wrong with my query. Can anybody help please?
I'm using Google App Engine and I created an persistent entity using Google documentation about JDO. The class is the following:
#PersistenceCapable
public class Message {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
public long id;
#Persistent
public Text message;
#Persistent
public boolean isNew;
#Persistent
public long categoryId;
#Persistent
public boolean plus;
#Persistent
public Date lastUpdate;
Message(long id, String message, boolean isNew, long categoryId, Date lastUpdate, boolean plus) {
this.id = id;
this.message = new Text(message);
this.isNew = isNew;
this.categoryId = categoryId;
this.lastUpdate = lastUpdate;
this.plus = plus;
}
}
And than, I create the a HttpServlet with the following doPost code:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
Date tenDaysAgo = new Date(new Date().getTime()-TEN_DAYS_IN_MILISSECOND);
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Query queryMessages = pm.newQuery(Message.class);
queryMessages.setFilter("isNew == True && lastUpdate <= lastUpdateParam");
queryMessages.declareParameters(Date.class.getName() + " lastUpdateParam");
List<Message> results = (List<Message>) queryMessages.execute(tenDaysAgo);
for(Message msg : results) {
msg.isNew = false;
pm.makePersistent(msg);
}
//pm.makePersistentAll(results);
writer.print(results.size() + " messages changed.");
}finally {
pm.close();
}
}
But, when I do a post request I receive the message "3048 messages changed." and I check the database and the data is unchanged. The persistence is not working to persist the changes I made in the object. Even though using makePersistentAll( list ) or makePersistent( object ) the result is the same: no change in the database.
What I'm missing?
Thank you!
You need to create a JDO transaction to keep track of changes and then commit them to issue the update SQL statements:
pm.currentTransaction().begin();
for(Message msg : results) {
msg.isNew = false;
}
pm.currentTransaction().commit();