我正在尝试学习如何使用Spring MVC和Hibernate构建应用程序。目前,我不得不将复选框值插入MySQL数据库。
我的数据库表结构如下:
id name interest
当我填写表单并点击提交时,我收到以下错误消息:
根本原因
java.sql.SQLException:字符串值不正确:' \ xAC \ xED \ x00 \ x05ur ...'对于列'兴趣'在第1行 com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1084) com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4232)
我正在尝试在表格中插入值,以便在插入后如下所示:
id name interest
1 Steve PHP
2 Steve Java
3 Wuagh C#
4 Wuagh PHP
你能告诉我如何实现这个目标吗?如果可能的话,你能否告诉我如何实现这一目标呢?
id name interest
1 Steve PHP, Java
2 Wuagh C#, PHP
请参阅下面的代码
我的表格:
<c:url var="action" value="/register" ></c:url>
<form:form action="${action}" modelAttribute="subscriber" method="POST" >
<div>
<label>Name</label>
<form:input path="name"/>
<form:errors path="name" cssClass="error"/>
</div>
<div>
<label>Interests</label>
<form:checkboxes path="interest" items="${records.interests}"/>
</div>
<input type="submit" value="Submit">
</form:form>
控制器:
package com.spring.org;
@Controller
public class HomeController {
@Autowired
private SubscriberService subService;
@RequestMapping(value="/register", method= RequestMethod.GET)
public ModelAndView RegistrationForm(@ModelAttribute Subscriber subscriber, BindingResult result)
{
HashMap<Integer, String> interest = new HashMap<Integer, String>();
interest.put(1,"Java");
interest.put(2,"PHP");
interest.put(3, "C#");
return new ModelAndView("regForm", "records", interest);
}
@RequestMapping(value="/register", method= RequestMethod.POST)
public ModelAndView RegistrationFormSubmit(@ModelAttribute("subscriber") @Valid Subscriber subscriber, BindingResult result)
{
if (result.hasErrors()) {
return new ModelAndView("regForm");
}
else
{
subService.addSubscriber(subscriber);
return new ModelAndView("redirect:/showList");
}
}
}
模型 - 订阅者
@Entity
@Table(name = "PERSON", schema = "java2")
public class Subscriber {
@Id
@Column(name="ID")
@GeneratedValue
private int id;
@NotEmpty(message = "Please enter your Name.")
private String name;
private String[] interest;
public String getName() {return name;}
public void setName(String name) { this.name = name; }
public String[] getInterest() { return interest; }
public void setInterest(String[] interest) { this.interest = interest; }
}
订阅服务实施:
@Service
public class SubscriberServiceImpl implements SubscriberService{
@Autowired
private SubscriberDao subsDao ;
@Override
public void addSubscriber(Subscriber subscriber) {
subsDao.addSubscriber(subscriber);
}
}
SubscriberDao实施:
@Repository
public class SubscriberDaoImpl implements SubscriberDao {
@Autowired
private SessionFactory sessionFactory ;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void addSubscriber(Subscriber subscriber) {
getSessionFactory().openSession().save(subscriber);
}
}