0

IN hibernate JPA how can I update of a object? I have one Project entity having two attributes. projectid and projectname. Here projectid is primary key. Now in my update method i should be able to modify both the attributes projectid and projectname. The query shouldl look like the in the following way.

update PROJECT set ID='123',NAME='Intel' where ID='122'

I want to assign the project_id to the user_id.

project_table
-------------
project_id  project_name  
-------------------------  
LK987       LockSystem  
MK876       MockSystem      


user_project_table
---------------------  
user_id        project_id  
--------------------------  
12343       LK987  
12344       MK876  
12343       TK656  
12675       TK656  
user414967
  • 5,225
  • 10
  • 40
  • 61

2 Answers2

2

Stop thinking in SQL, start thinking in EntityManager. Project p = entityManager.find(Project.class, 122); p.setId(123); p.setName("Intel"); entityManager.merge(p);

That said, it's almost always the wrong choice to change an entity's primary key.

Why would you change an entity's identity? You'd also need to update all the foreign keys in other tables that point to it. Seems like a pain, with no gain. You're probably better off making this a "business key" (plain property) and using a more permanent surrogate key.

If you really need to be able to change a project's ID number, you should change the primary key to an autoincremented number. The entity would look something like this:

@Entity
public class Project
{
    @Id @GeneratedValue
    private int id;
    private int projectId;
    private String projectName;

    // getters and setters
}


So you want to associate projects to users.

You can either do it where the project id (a string, like "LK987") is the primary key (which, by now I'm sure you understand you should not change) — or you can use a separate autoincrement int as the id. It's up to you; my personal preference is the autoincrement approach so you just don't have to worry about it later.

What you're trying to do is set up relationships between Project entities and User entities. Instead of storing foreign key fields, you should store entity fields (for one-to-one, one-to-many, or many-to one mappings) or collections of entities (for one-to-many, many-to one, or many-to-many mappings). If I understand what you need:

  • Each user can have multiple projects, and each project can have multiple users (so that mapping is many-to-many)
  • Users know about projects, and projects might as well know about users (so the mapping is bidirectional). I'll assume that the User is the owner of the relationship, and the Project is the inverse side.

That means you'll to use the @ManyToMany annotation, and specify a @JoinTable and which @JoinColumns to use.

User entity class

@Entity
public class User
{
    @Id @GeneratedValue
    int id;  // the PK for user entities

    @ManyToMany
    @JoinTable(
        name="user_project_table",
        joinColumns=@JoinColumn(name="user_id"),
        inverseJoinColumns=@JoinColumn(name="project_id"))
    Set<Project> projects;

    // snip...
}

Project entity class

@Entity
public class Project
{
    @Id @GeneratedValue
    int id;
    String projectId;
    String projectName;

    @ManyToMany(mappedBy="projects")
    Set<User> users;

    // snip...
}

Notice how we're using full-fledged entity classes, not just foreign keys.

Further reading from The Java EE 6 Tutorial:

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • +1 for the end of the answer. The start is a bit dodgy at this moment. – Aleksi Yrttiaho Jun 11 '11 at 17:44
  • Hi Matt.Thanks for your information.I want to assign the projectid to the userid. How do I assign the project id to the user id? Which one should I assign project_id or autoincrement generated id? How Do I desgin both the tables And probably the project id will be the type of String. For me I should be able to modify the project_id for sure,because if the user might enter wrong project_id and if he/she needs to change the project_code later it should be helpful in edit option. – user414967 Jun 12 '11 at 04:56
  • When you say _"I want to assign the projectid to the userid"_ do you mean that you want to be able to associate projects to users? As for _"Which one should I assign"_ are you asking about changing the value of `project_id` or the autoincrement id? **Never. Change. The. Primary. Key.** – Matt Ball Jun 12 '11 at 05:27
  • Yes I want to associate projects to users. In that case how does it make a relationship between user and project? If I want to make the relationship,I need to define the project_id as PK. So this PK will be the FK in users table for finding out the how many projects associated to the user. Though we are talking about the update the project id,I totally confused the way of designing. Please make me understand. I understook that PK should never change. – user414967 Jun 12 '11 at 06:14
  • Okay, I follow. There's a better way than worrying about foreign keys. Remember the first sentence of my answer? It still applies. In JPA, you can/should replace fields which store foreign keys with fields that store entities (or collections of entities). I'm editing my answer accordingly, but basically you need to know about [`@OneToOne`](http://download.oracle.com/javaee/6/api/javax/persistence/OneToOne.html) and/or [`@OneToMany`](http://download.oracle.com/javaee/6/api/javax/persistence/OneToMany.html). Can each user only have a single project, or can each user have multiple projects? – Matt Ball Jun 12 '11 at 06:39
  • Can each project have multiple users as well? That would be more like a [`@ManyToMany`](http://download.oracle.com/javaee/6/api/javax/persistence/ManyToMany.html). At any rate, you should probably create a separate [join table](http://en.wikipedia.org/wiki/Join_table) to associate projects and users. – Matt Ball Jun 12 '11 at 06:40
  • Yes,each user can have multiple projects and each projects can have multiple users. And one more thing I would like to mention here is When the user is created,none of the projects are assigned. After the user is created,there is one page for assigning users to the project.There only I assign the Projects to the users. – user414967 Jun 12 '11 at 06:51
  • Ok, I missed that you're already using a join table (sorry!). I'm still editing my answer... – Matt Ball Jun 12 '11 at 06:57
  • Hi Matt, Thanks a lot for your valuable effort. I am almost clear about the concepts. Let me go again through the relation ships. Then I will make a post here. Thanks a lot again. – user414967 Jun 12 '11 at 07:29
2

If project id is the primary key and the identifier of an object, you should never change it. Change of primary key means that the represented object changes to something entirely different.

JPA assumes that the primary key is fixed. The read, updated and delete operations identifies the object in question by it's id. If you change the id of an object and execute an update, JPA either updates some completely different object (and this might result in an exception) or doesn't find an object to update at all.

To emphasize this, JPA spec forbids the change of primary key. Hibernate may also exclude the primary key from any generated update statement. See page 28 of JSR-317

The value of its primary key uniquely identifies an entity instance within a persistence context and to EntityManager operations as described in Chapter 3, “Entity Operations”. The application must not change the value of the primary key (this includes not changing the value of a mutable type that is primary key or an attribute of a composite primary key). The behavior is undefined if this occurs (the implementation may, but is not required to, throw an exception. Portable applications must not rely on any such specific behavior).

To accomplish the desired result, you should delete the old object and create a new one.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
Aleksi Yrttiaho
  • 8,266
  • 29
  • 36