开发者

How did spring MVC send data to Model Obj with hibernate

I have

class Person  {

@OneToMany(cascade = CascadeType.ALL)
 @JoinTable(name = "person_countries", joinColumns = { @JoinColumn(name = "person_id") }, 
         inverseJoinColumns = { @JoinColumn(name = "country_id") })
 private List<Country> countries ; 

Class country {

@Id
@Column(name = "country_id")
@GeneratedValue
private  Integer country_id;


@Column(name = "country_name")
private String country_name;

Now i am showing checkboxes in form so that user can select more than one countries. but i am confused开发者_开发知识库 how will that form send country object to person.

addpage.jsp

<form:form modelAttribute="personAttribute" method="POST" action="${saveUrl}">

<form:checkboxes path="countries" items="${countryList}" itemValue="country_id" itemLabel="country_name" />

This is the html which is generated

<label for="countries2">uk</label></span><span><input id="countries3" name="countries" type="checkbox" value="3"/>

but i am confused how will that data store country obj in person i mean which value hibernate need to store in relation ship table its value or label because country name is already in database. i just need to store its id.

i am confused how will mapping take place. because i am not entering country name. They already present in database


When spring binds the form with an object, it instantiates the object (you can plug in your own creation process as well).

So the object is filled with all the required data, but it in detached state (it does not belong to a hibernate session)

When you merge the object into hibernate it tries to load existing entities that have the same ID as the one specified in your detached object. If there are such - they are loaded and used.

That's how things work in general. In your case the HTML should submit only the country ID, then that country should be loaded from the database (via hibernate), and set into the user object.

You can do this in an @InitBinder method, by registering a custom property editor - one which, given a country id, loads the entire country object..


In the relationship tbl, it shd store value of chkbox, ie country_id, as per the rules normalization..U need not to enter contry name, as these will get fetched with your @Jointable annotation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜