简体   繁体   中英

Hibernate One-to-Many Mapping Using Annotations; I'm trying to use foreign key association to save a user id in another table.

I'm not able to make this work. I've also tried using a join table, but the result is the same. The user id that I need to appear in the table commissions doesn't.

Here's how I've created the entities.

For User and UserRole I've used a join table and it works. I've tried to do the same for Commission but with no success (the joining table remained empty) so I tried like below with foreign key association.

User:

@Entity
@Table(name="USERS")
public class User implements Serializable{

/**
 * serialVersionUID
 */
private static final long serialVersionUID = 1L;

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;

@NotEmpty
@Column(name="USERNAME", unique=true, nullable=false)
private String username;

@NotEmpty
@Column(name="PASSWORD", nullable=false)
private String password;

@NotEmpty
@Column(name="FIRST_NAME", nullable=false)
private String firstName;

@NotEmpty
@Column(name="LAST_NAME", nullable=false)
private String lastName;

@NotEmpty
@Column(name="EMAIL", nullable=false)
private String email;

@NotEmpty
@ManyToMany(targetEntity=UserRole.class, fetch = FetchType.LAZY)
@JoinTable(name = "USERS_USER_ROLE", 
         joinColumns = { @JoinColumn(name = "USER_ID") }, 
         inverseJoinColumns = { @JoinColumn(name = "USER_ROLE_ID") })
private Set<UserRole> userRoles = new HashSet<UserRole>();

@OneToMany(fetch = FetchType.LAZY, mappedBy="user") 
private Set<Commission> commissions;

//getters and setters

Commission:

@Entity
@Table(name="COMMISSIONS")
public class Commission implements Serializable{

/**
 * serialVersionUID
 */
private static final long serialVersionUID = 1L;

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;

@NotEmpty
@Column(name="ORDER_NAME", unique=true, nullable=false)
private String orderName;

@NotEmpty
@Column(name="ORDER_DETAILS", unique=true, nullable=false)
private String orderDetails;

@Column(name="ORDER_STATUS", unique=true, nullable=false)
private String orderStatus;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID", nullable = false)
private User user;

//getters and setters

UserRole:

@Entity
@Table(name="USER_ROLE")
public class UserRole implements Serializable{

/**
 * serialVersionUID
 */
private static final long serialVersionUID = 1L;

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id; 

@Column(name="ROLE", length=15, unique=true, nullable=true)
private String role = UserRoleType.USER.getUserRoleType();  // getUserRoleType is defined in an enum with 'ADMIN', 'DBA', 'USER'

//getters and setters

In the UserDAO and CommissionDAO I've used SessionFactory to save the entities.

Extract from the abstract class which is extended by UserDAO and CommissionDAO.

@Autowired
private SessionFactory sessionFactory;

protected Session getSession(){
    return sessionFactory.getCurrentSession();
}

public void persist(T entity) {
    getSession().save(entity);
}

When I create a new user, everything works fine. The joining table has the correct id's added to it. However... When I add a new commission, the commission itself is added in the commissions table but the user_id remains null.

I'm new to hibernate and with this "project" of mine, I think I might've bit a more than I can chew.

Maybe the issue is somewhere else in the code and not here?

Anyhow, I'm in a bit of a bind and could use your expertise guys. Cheers!

Thanks Rossi Robinsion. That was it.

I missed to associate the user in my Commission controller. This was before.

@RequestMapping(value = { "/newcommission" }, method = RequestMethod.POST)
public String saveCommission(@Valid Commission commission, BindingResult result, ModelMap model) {

    if (result.hasErrors()) {
        return "commissioncreation";
    }

    if(!commissionService.isUserOrderNameUnique(commission.getId(), commission.getOrderName())){
        FieldError orderNameError =new FieldError("commission","orderName", 
                messageSource.getMessage("non.unique.orderName", 
                        new String[]{commission.getOrderName()}, Locale.getDefault()));
        result.addError(orderNameError);
        return "commissioncreation";
    }

    commissionService.saveCommission(commission);

    model.addAttribute("success", "Your commission was successfully created.");
    model.addAttribute("loggedinuser", getPrincipal());
    return "commissioncreationsuccess";
}

This is after.

@RequestMapping(value = { "/newcommission" }, method = RequestMethod.POST)
public String saveCommission(@Valid Commission commission, BindingResult result, ModelMap model) {

    if (result.hasErrors()) {
        return "commissioncreation";
    }

    if(!commissionService.isUserOrderNameUnique(commission.getId(), commission.getOrderName())){
        FieldError orderNameError =new FieldError("commission","orderName", 
                messageSource.getMessage("non.unique.orderName", 
                        new String[]{commission.getOrderName()}, Locale.getDefault()));
        result.addError(orderNameError);
        return "commissioncreation";
    }

    User user = userService.findByUsername(getPrincipal()); // associated the user properly.
    commission.setUser(user);

    commissionService.saveCommission(commission);

    model.addAttribute("success", "Your commission was successfully created.");
    model.addAttribute("loggedinuser", getPrincipal());
    return "commissioncreationsuccess";
}

I don't know how I could miss this... sigh...

Thanks mate!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM