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 @JoinColumn
s 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.