Reputation: 377
I have an Agent class and a User class which extends Agent. I would like to cast a persisted Agent to a User and persist the user using the same id, name and firstname. I don't what to insert an other line into Agent table. How can I do that ?
Here are my classes.
@Entity
@Table(name = "agent")
@Inheritance(strategy = InheritanceType.JOINED)
public class Agent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Integer id;
@Column(name = "fistname", nullable = false)
protected String fistname;
@Column(name = "name", nullable = false)
protected String name;
}
@Entity
@Table(name="user")
public User extends Agent{
@Column(name = "login", nullable = false, unique = true)
public String login;
@Column(name = "password", nullable = false)
public String password;
I would like to do that
Agent agent=agentService.findOne(1);
User user = new User(agent);
user.setLogin("login");
...
user=userService.saveAndFlush(user);
ok = user.getId() == agent.getId();
To sum up I'd like to grant an Agent to a User when I need it.
Upvotes: 1
Views: 966
Reputation: 377
I've tought doing this. It's working but I lose the fact that a user is a specialized Agent.
@Entity
@Table(name = "agent")
@Inheritance(strategy = InheritanceType.JOINED)
public class Agent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Integer id;
@Column(name = "fistname", nullable = false)
protected String fistname;
@Column(name = "name", nullable = false)
protected String name;
}
@Entity
@Table(name="user")
public User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Integer id;
@OneToOne
@JoinColumn(name = "id_agent",nullable = false)
protected Agent agent;
@Column(name = "login", nullable = false, unique = true)
private String login;
@Column(name = "password", nullable = false)
private String password;
Upvotes: 0
Reputation: 1530
You can't cast an Agent to a User, but you can build a user from an Agent by setting the Agent's properties in the User propeties, unless you have added a copy constructor from Agent ->User in the User class, in both cases a new User will be created and a new row will be added.
Upvotes: 1