Hibernate Model:设置Child Class的默认@ManyToOne值

时间:2014-06-27 07:27:11

标签: java hibernate default-value class-hierarchy

我有一个具有@ManyToOne字段角色的类User。

@Entity 
@Table(name="USERS")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorValue("ROLE_ADMIN")
@DiscriminatorColumn (name="ROLENAME", discriminatorType= DiscriminatorType.STRING, length=20)
public class User extends BaseEntity implements UserDetails {
    // all others fields like username, password,...

    @ManyToOne
    @JoinColumn(name = "role_id", referencedColumnName="id") 
    @NotNull(message = "ROLE field is mandatory")
    private Role role;

    //getter and setter
}

我有许多扩展用户的类:UserSeller,UserClient,UserOffice ....

@Entity
    @DiscriminatorValue("ROLE_SELLER")
    @AttributeOverride(name = "role", column = @Column(name = "role_id"))
    public class UserSeller extends User {

       //additional fields like CompanyId,...

       //getter & setter
    }

我有一个面板,我可以插入/编辑/删除所有类型的用户, 但我必须也有“n”面板:每种用户都有一个。

当我在这些面板中时,我希望能够无需插入这些UserSeller 放置一个选择角色的位置,但我想将此角色设置为默认值。

•我试图在UserSeller中放置一个costructor

@Entity
@DiscriminatorValue("ROLE_SELLER")
@AttributeOverride(name = "role", column = @Column(name = "role_id"))
public class UserSeller extends User {

    @Transient
    RoleService roleService;

    @Transient
    User user = new User();


    public UserSeller()
    {
        super(); 
        try
        {
            this.setRole(roleService.getRole("ROLE_SELLER"));
        }
        catch (RecordNotFoundException e)
        {

        }
    }

但是我收到了这个错误:

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

•我试图将User对象传递给构造函数:

public UserSeller(User user)

在控制器中我这样做:

 User user = new User();
 UserSeller seller = new UserSeller(user);
 model.addAttribute("seller", seller);

但是我收到了这个错误:

  

没有实体的默认构造函数:com.machinet.model.UserVenditore

  • 如果在UserSeller中再次声明了Role字段,我会收到错误消息 “重新定义的专栏”....

  • 最后我发现这个我可能是我的解决方案(in UserSeller类):

    @PrePersist
    public void prePersist() {
            try
            {
                this.setRole(roleService.getRole("ROLE_SELLER"));
            }
            catch (RecordNotFoundException e)
            {
    
            }           
        }
    

但是当我在UserSeller面板中并且我尝试添加新的卖家时,它不会采取默认角色并且验证失败。

我想知道我该怎么做:我希望我的UserSeller,UserClient,...在插入新记录时有一个默认值。

我真的需要在控制器中执行此操作吗?这是唯一的方法吗?因为对于像我这样的初学者来说,它看起来并不是那么优雅的解决方案:

UserVenditore venditore = new UserVenditore();
try
{
    venditore.setRole(roleService.getRole("ROLE_VENDITORE"));
}
catch (RecordNotFoundException ex)
{

}
model.addAttribute("venditore", venditore);

编辑:这最后一个解决方案也不起作用:验证失败!

感谢您的任何建议!

1 个答案:

答案 0 :(得分:0)

现在,我发现只有这个解决方案(在ControllerClass中):

  • 在@ModelAttribute
  • 之前删除了@Valid
  • 我手动设置角色
  • 我手动验证对象

    @RequestMapping(value =“/ add”,method = RequestMethod.POST) public String addingSeller(@ModelAttribute UserSeller卖家,         BindingResult结果,RedirectAttributes redirectAttrs){

    logger.info("IN: Seller/add-POST"); 
    
    //set role
    try
    {
        seller.setRole(roleService.getRole("ROLE_SELLER"));
    }
    catch (RecordNotFoundException ex)
    {
    
    }        
    
    //validation
    validator.validate(seller, result);
    
    if (result.hasErrors()) {
        logger.info("Seller-add error: " + result.toString());
        redirectAttrs.addFlashAttribute("org.springframework.validation.BindingResult.seller", result);            
        redirectAttrs.addFlashAttribute("seller", seller);
    
    } else {
    
        try
        {
            SellerService.addSeller(seller);
    
            //message to the user
            String message = "Seller added!";           
            redirectAttrs.addFlashAttribute("message", message);
            redirectAttrs.addFlashAttribute("message_class", "alert-success");      
        }
        catch (DuplicateRecordException e)
        {
            //the username already exists
    
            //message to the user
            String message = "Already exists an user with this USERNAME";           
            redirectAttrs.addFlashAttribute("message", message);
            redirectAttrs.addFlashAttribute("message_class", "alert-danger");         
    
            redirectAttrs.addFlashAttribute("seller", seller);
        }
    }   
    
    return "redirect:/sellers/list";
    

    }