Java MVC和带有集合的对象<&燃气轮机;

Java MVC和带有集合的对象<&燃气轮机;,java,spring,hibernate,jsp,spring-mvc,Java,Spring,Hibernate,Jsp,Spring Mvc,我有两个类映射到Hibernate中。 1.该类实现了帐户 2.该类实现帐户的类型。 重要!一个帐户可以有多种类型 Account.class @Entity @Table(name = "dp_account", uniqueConstraints={@UniqueConstraint(columnNames={"id"})}) public class Account { @Id @C

我有两个类映射到Hibernate中。
1.该类实现了帐户
2.该类实现帐户的类型。
重要!一个帐户可以有多种类型

 Account.class
    @Entity
    @Table(name = "dp_account",
            uniqueConstraints={@UniqueConstraint(columnNames={"id"})})
        public class Account {

            @Id
            @Column(name="id", nullable = false, unique = true, length = 11)
            @GeneratedValue(strategy = GenerationType.AUTO)
            private long id;

            @Column(name = "price", nullable = false)
            private int price;

            @Column(name = "customer_id", nullable = false, unique = true, length = 11)
            private long customerId;

            @Column(name = "customer", length = 100, nullable = false, unique = true)
            private String customer;

            @Column(name = "comment", length = 1000)
            private String comment;

            @Column(name = "date", columnDefinition="TIMESTAMP")
            @Temporal(TemporalType.TIMESTAMP)
            private Date date;

            @Column(name = "is_deleted", nullable = false)
            private boolean deleted = false;

            @ManyToMany(fetch = FetchType.EAGER, targetEntity = AccountType.class, cascade = { CascadeType.ALL })
            @JoinTable(name = "account_accountType",
                    joinColumns = { @JoinColumn(name = "account_id") },
                    inverseJoinColumns = { @JoinColumn(name = "type_id") })
            private Set<AccountType> accountTypes;
        // дальше конструкторы и геттеры/сеттеры
        }
问题是-有一个页面,我填写表格创建帐户 (
Account.class
),我会选择多个
来填充帐户类型
(
AccountType.class
)。Account.class已设置字段<代码>

更新:

@RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public ModelAndView welcomePage() {
        ModelAndView model = new ModelAndView();
        List<GrantedAuthority> grantedAuthorityList = (List<GrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String login = authentication.getName();
        if (grantedAuthorityList.contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) {
            model.setViewName("admin");
        } else {
            List<AccountType> accountTypes = ServiceFactory.getInstance().getAccountService().getAllAccountTypeByLogin(login);
            model.addObject("accountTypes", accountTypes);
            model.setViewName("user");
        }
        return model;
    }
@RequestMapping(value=“/welcome”,method=RequestMethod.GET)
公共模型和视图welcomePage(){
ModelAndView模型=新的ModelAndView();
List grantedAuthorityList=(List)SecurityContextHolder.getContext().getAuthentication().GetAuthority();
身份验证=SecurityContextHolder.getContext().getAuthentication();
String login=authentication.getName();
if(grantedAuthorityList.contains(新的SimpleGrantedAuthority(“角色\管理员”)){
model.setViewName(“管理员”);
}否则{
List accountTypes=ServiceFactory.getInstance().getAccountService().getAllAccountTypeByLogin(登录名);
model.addObject(“accountTypes”,accountTypes);
model.setViewName(“用户”);
}
收益模型;
}

您正在使用html select元素,但您需要做的是使用spring标记库的select,即:

<form:select path="accountTypes" multiple="true">
  <form:options items="${accountTypes}"/>
</form:select>

这样,spring将绑定控制器中的值

试试这个

@RequestMapping(value = "/welcome", method = RequestMethod.GET)
public ModelAndView welcomePage() {
    ModelAndView model = new ModelAndView();
    List<GrantedAuthority> grantedAuthorityList = (List<GrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String login = authentication.getName();
    if (grantedAuthorityList.contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) {
        model.setViewName("admin");
    } else {
        List<AccountType> accountTypes = ServiceFactory.getInstance().getAccountService().getAllAccountTypeByLogin(login);
        model.addObject("accountTypes", accountTypes);
        model.setViewName("user");
//Add here
model.addObject("accountAttribute", new Account());
    }
    return model;
}
@RequestMapping(value=“/welcome”,method=RequestMethod.GET)
公共模型和视图welcomePage(){
ModelAndView模型=新的ModelAndView();
List grantedAuthorityList=(List)SecurityContextHolder.getContext().getAuthentication().GetAuthority();
身份验证=SecurityContextHolder.getContext().getAuthentication();
String login=authentication.getName();
if(grantedAuthorityList.contains(新的SimpleGrantedAuthority(“角色\管理员”)){
model.setViewName(“管理员”);
}否则{
List accountTypes=ServiceFactory.getInstance().getAccountService().getAllAccountTypeByLogin(登录名);
model.addObject(“accountTypes”,accountTypes);
model.setViewName(“用户”);
//加在这里
addObject(“accountAttribute”,new Account());
}
收益模型;
}

问题在于,您需要注册一个属性编辑器或转换器,该编辑器或转换器能够将您的帐户类型名称转换为AccountType对象。您的视图发送accountTypes元素的字符串值。Spring需要知道如何将字符串值绑定到对象

public class AccountTypeEditor extends PropertyEditorSupport{

   public void setAsText(String text){
        AccountType accountType = // some logic to find account type by name
        setValue(accountType);
   }
}
在控制器中,需要@InitBinder方法来注册编辑器

@InitBinder
public void initBinder(WebDataBinder binder){
   binder.registerCustomEditor(AccountType.class , new AccountTypeEditor());
}

}

我能够解决这个问题,我开始分别传递Set和object本身帐户。问题是,我从jsp帐户传递,我想设置,这是不可能的,因为我只选择了名称类型帐户。这是我的问题的解决方案:

JSP:


Сумма: 


${accountType} Комментарий:



控制器:

@RequestMapping(value = "/account/addAccount", method = RequestMethod.POST)
    public void addAccount(@ModelAttribute("accountAttribute") Account account, @RequestParam(value="accountTypeNameSet") Set<String> accountTypeNameSet) {
    // implementation here
// accountTypeNameSet - This is the list of names account type, which user selected. On the basis of these names we can pull your invoice from database. 
@RequestMapping(value=“/account/addAccount”,method=RequestMethod.POST)
public void addAccount(@modeldattribute(“accountAttribute”)Account Account,@RequestParam(value=“accountTypeNameSet”)Set accountTypeNameSet){
//在这里实现
//accountTypeNameSet-这是用户选择的帐户类型名称列表。根据这些名称,我们可以从数据库中提取您的发票。

谢谢您的回答,但当我使用您的解决方案时,我遇到了一个问题“java.lang.IllegalStateException:bean名称“accountAttribute”的BindingResult和普通目标对象都不能作为请求属性使用”这可能是因为您没有将accountAttribute添加到控制器中的模型中,该模型返回您作为屏幕截图附加的页面。请在我的问题中查看MVC控制器。我认为我添加了accountAttribute。我错了吗?您发布的控制器方法映射到您附加页面的提交操作,对吗?我说的是让你进入表单页面的控制器功能的变化。你看到我更新的答案了吗?老实说,我真的不明白这个控制器是什么。我有一个表单,它创建了一个对象,并为这个控制器做了什么?如果有兴趣,我能够解决这个问题。我做了一个replY
public class AccountTypeEditor extends PropertyEditorSupport{

   public void setAsText(String text){
        AccountType accountType = // some logic to find account type by name
        setValue(accountType);
   }
}
@InitBinder
public void initBinder(WebDataBinder binder){
   binder.registerCustomEditor(AccountType.class , new AccountTypeEditor());
}
<form:form action="${pageContext.request.contextPath}/account/addAccount" method="post" modelAttribute="accountAttribute">

                <label>
                    Сумма: <input type="number" name="price">
                </label>
                <br> <br>

                <select multiple name="accountTypeNameSet" size="4s">
                    <c:forEach items="${accountTypes}" var="accountType">
                        <option >${accountType}</option>
                    </c:forEach>
                </select>

                <label>Комментарий:
                    <br> <br>
                    <textarea name="comment" rows="5" cols="30"></textarea>
                </label>
                <br><br>

                <input type="submit" value="Внести">

            </form:form>
@RequestMapping(value = "/account/addAccount", method = RequestMethod.POST)
    public void addAccount(@ModelAttribute("accountAttribute") Account account, @RequestParam(value="accountTypeNameSet") Set<String> accountTypeNameSet) {
    // implementation here
// accountTypeNameSet - This is the list of names account type, which user selected. On the basis of these names we can pull your invoice from database.