description The server encountered an internal error () that prevented it from fulfilling this request
功能:加入一个sno=1 cno=1的数据到sc表中
Java code?package stu.course.com; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; /** * * @author Administrator */@WebServlet(name = "XuankeServer", urlPatterns = {"/XuankeServer"}) public class XuankeServer extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Configuration cfg = new Configuration().configure(); SessionFactory sf = cfg.buildSessionFactory(); Session session = sf.openSession(); Transaction ts = session.beginTransaction(); SC sc=new SC(); sc.setSno(1); sc.setCno(1); session.save(sc); ts.commit(); session.close(); } }
配置文件
1.hibernate.cfg.xml
Java code?<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/ssc</property> <property name="connection.username">root</property> <property name="connection.password">111111</property> <property name="show_sql">true</property> <mapping resource="Student.hbm.xml"/> <mapping resource="sc.hbm.xml"/> </session-factory> 2.sc.hbm.xml </hibernate-configuration>
Java code?<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="stu.course.com.SC" table="sc"> <id name="sno"> <generator class="native"/> </id> <property name="cno"/> </class> </hibernate-mapping>
报错:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
Field 'sno' doesn't have a default value sno 没有默认值,也就是你的sc.setSno(1);这个可以去掉
sno设置了native,就是交由数据库管理,你可以在数据库放将其设置为自动增长,然后你的项目就不需要设置sno的值,直接添加cno就可以了
<id name="sno"> <generator class="native"/> </id>
是这样配的吗?
改为assigned 就可以手动指定.
native 会使hibernate 根据数据库生成策略去指定的,跟你有没有set这个值没有关系.
搞了两个小时都没搞定原来是这个原因 吧native参数改成assigned就行了