hibernate、mysql 中关于boolean映射的问题

hibernate3、mysql5.5:
javaBean中字段为Boolean
hibernate映射文件中设置byte 数据库中设置tinyint 报错
Hibernate映射文件中设置yes_no 数据库中设置varchar(1) 仍然报类型转换 错误

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
用Hibernate映射mysql问题(Timestamp)

我知道这个是个常见问题,我已经看了论坛帖子和查阅相关资料,始终没找到好的解决方法,如果有空的帮解答下吧。 SessionInfo.hbm.xml [code="java"]<hibernate-mapping package="domaininvestment.model"> <class name="SessionInfo" table="SessionInfo"> <id name="id"> <generator class="native" /> </id> <property name="email" type="string" length="500" not-null="true" /> <property name="sessionID" type="string" length="200" /> <property name="clientIP" type="string" length="200" not-null="true" /> <property name="creationTime" type="timestamp" not-null="true" /> </class> </hibernate-mapping>[/code] SessionInfoDao.java [code="java"]public boolean sessionInfoExists(SessionInfo info) throws RuntimeException { if (info == null) { return false; } Session sess = DaoBase.currentSession(); try { String infoEmail = info.getEmail(); String infoClientIP = info.getClientIP(); Date infoCreationTime = info.getCreationTime(); if (infoEmail == null || infoClientIP == null || infoCreationTime == null) { return false; } int diff = Util.diffDays(new Date(), infoCreationTime); if (diff < 0 || diff > SessionInfo.COOKIE_MAX_DAYS) { return false; } Query q = sess.createQuery("from SessionInfo where email = :email and clientIP = :clientIP and creationTime =:creationTime") .setString("email", infoEmail) .setString("clientIP", infoClientIP) .setStrng("creationTime", infoCreationTime); Iterator itr = q.iterate(); if (itr.hasNext()) { return true; } else { return false; } } finally { DaoBase.closeSession(); }[/code] SessionInfoDaoTest.java [code="java"]@Test public void testSessionInfoExists() { SessionInfo info = null; assertFalse(dao.sessionInfoExists(info)); info = new SessionInfo(); assertFalse(dao.sessionInfoExists(info)); info.setEmail("test@dc.com"); assertFalse(dao.sessionInfoExists(info)); info.setSessionID("123456"); assertFalse(dao.sessionInfoExists(info)); info.setClientIP("192.168.1.1"); assertFalse(dao.sessionInfoExists(info)); info.setCreationTime(new Date()); assertFalse(dao.sessionInfoExists(info)); info = new SessionInfo(); info.setEmail("test@dc.com"); info.setClientIP("192.168.1.1"); info.setCreationTime(new Date()); Session sess = reopenSession(); sess.save(info); sess.flush(); closeSession(); assertTrue(dao.sessionInfoExists(info)); }[/code] 这里主要是timeStamp的问题,如果我把hql里面的creationTime去掉,即:"from SessionInfo where email = :email and clientIP = :clientIP " 我的测试就没问题,我把它加上后即使转成sqlDate也没用,不知道问题出在哪里?

mysql int类型值为null,hibernate映射错误的问题

我mysql数据库 有一个  numBack字段 ,是 int 类型的 , <br /> <br />hibernate中 用  private int numBack; 与它对应 <br /> <br /> <br />        &lt;property name="numBack" column="numBack" type="int" length="5"&gt; <br />但当  数据库中 它的值是  NULL时 , <br /> <br />就会报错 。 <br /> <br />我想请问一下在  不把  数据库中  NULL改成 0的情况下, hibernate有没有什么措施可以解决 ?

JPA 一对多单向 映射至Mysql的问题

<p>角色Role与权限Authority,我设计成一对多单向关联,数据库mysql: <br><br>//Role.java:</p> <pre name="code" class="java">@Entity public class Role implements Serializable { private Integer roleid; private String rolename; private String description; private Set&lt;Authority&gt; auths = new HashSet&lt;Authority&gt;(); @Column public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Id @GeneratedValue public Integer getRoleid() { return roleid; } public void setRoleid(Integer roleid) { this.roleid = roleid; } @Column public String getRolename() { return rolename; } public void setRolename(String rolename) { this.rolename = rolename; } <span style="color: #ff0000;">//一对多单向关联</span> <span style="color: #0000ff;">@OneToMany(cascade = CascadeType.REFRESH, fetch=FetchType.EAGER) @JoinTable(name = "role_auth", joinColumns = @JoinColumn(name = "roleid"), inverseJoinColumns = @JoinColumn(name = "authorityid")) public Set&lt;Authority&gt; getAuths() { return auths; } public void setAuths(Set&lt;Authority&gt; auths) { this.auths = auths; }</span> // 添加权限 public void addAuth(Authority auth) { this.auths.add(auth); } @Override public int hashCode() { ... } @Override public boolean equals(Object obj) { ... } } </pre> <p><br><br>//Authority.java:</p> <pre name="code" class="java">@Entity public class Authority implements Serializable { private Integer authorityid; // 范围 private Range range; // 动作 private Action action; public Authority() {} public Authority(Range range, Action action) { this.range = range; this.action = action; } @ManyToOne @JoinColumn(name="actionid", referencedColumnName="actionid") public Action getAction() { return action; } public void setAction(Action action) { this.action = action; } @Id @GeneratedValue public Integer getAuthorityid() { return authorityid; } public void setAuthorityid(Integer authorityid) { this.authorityid = authorityid; } @ManyToOne @JoinColumn(name="rangeid", referencedColumnName="rangeid") public Range getRange() { return range; } public void setRange(Range range) { this.range = range; } @Override public int hashCode() { ... } @Override public boolean equals(Object obj) { ... } } </pre> <p><br><br>生成的中间表为role_auth,查看建表语句:</p> <pre name="code" class="sql">mysql&gt; show create table user_role; | Table | Create Table | user_role | CREATE TABLE `user_role` ( `userid` int(11) NOT NULL, `roleid` int(11) NOT NULL, PRIMARY KEY (`userid`,`roleid`), <span style="color: #ff0000;">UNIQUE KEY `roleid` (`roleid`),//roleid为什么具有唯一性???</span> KEY `FK143BF46A889EC6EB` (`userid`), KEY `FK143BF46A83497181` (`roleid`), CONSTRAINT `FK143BF46A83497181` FOREIGN KEY (`roleid`) REFERENCES `role` (`rol eid`), CONSTRAINT `FK143BF46A889EC6EB` FOREIGN KEY (`userid`) REFERENCES `user` (`use rid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | 1 row in set (0.00 sec) </pre> <p><br><br>如上红色部分,roleid具有唯一性,这样我在插入角色时就会出现类似“Duplicate entry '2' for key 2”的错误。 <br>该怎么改呢??</p> <p> </p>

一个登录实例的hibernate 映射问题

这是一个hibernate+struts的登录实验。用的mySQL数据库,struts控制的前台没有问题,只是一登录就出现这种错误。 org.hibernate.hql.ast.QuerySyntaxException: user is not mapped. [FROM user AS u WHERE u.uerName=? AND u.password=?] at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:157) at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87) at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:70) at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:265) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3049) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2938) at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:688) at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:544) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229) at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:218) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:158) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:109) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:75) at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:54) at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:71) at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133) at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112) at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1583) at com.netBook.impl.userImpl.isUser(userImpl.java:30) at com.netBook.struts.action.LoginAction.insert(LoginAction.java:49) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:274) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:194) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:212) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:818) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:624) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445) at java.lang.Thread.run(Thread.java:619) Caused by: user is not mapped. ... 45 more 我的hibernate.cfg.xml为: <?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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/netbook</property> <property name="connection.username">root</property> <property name="connection.password">8936</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="myeclipse.connection.profile"> mySQLDatabase </property> <mapping resource="com/netBook/pojo/User.hbm.xml" /> </session-factory> </hibernate-configuration> 我的pojo类为: package com.netBook.pojo; public class User { private String userName; private String password; private String sex; private String telepone; private String Email; private String address; private String postalcode; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return Email; } public void setEmail(String Email) { this.Email = Email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPostalcode() { return postalcode; } public void setPostalcode(String postalcode) { this.postalcode = postalcode; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getTelepone() { return telepone; } public void setTelepone(String telepone) { this.telepone = telepone; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } 我的User.hbm.xml文件为: <?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"> <!-- Mapping file autogenerated by MyEclipse - Hibernate Tools --> <hibernate-mapping> <class name="com.netBook.pojo.User" table="user" catalog="netbook"> <id name="userName" type="java.lang.String"> <column name="userName" length="20" /> <generator class="assigned" /> </id> <property name="password" type="java.lang.String"> <column name="password" length="20" not-null="true" /> </property> <property name="sex" type="java.lang.String"> <column name="sex" length="5" not-null="true" /> </property> <property name="telepone" type="java.lang.String"> <column name="telepone" length="20" not-null="true" /> </property> <property name="Email" type="java.lang.String"> <column name="Email" length="40" not-null="true" /> </property> <property name="address" type="java.lang.String"> <column name="address" length="40" not-null="true" /> </property> <property name="postalcode" type="java.lang.String"> <column name="postalcode" length="10" not-null="true" /> </property> </class> </hibernate-mapping> session工厂为: package com.netBook.factory; import org.hibernate.Session; import org.hibernate.cfg.Configuration; public class sessionFactory { public static Session getSession(){ Session session=null; session = new Configuration().configure().buildSessionFactory() .openSession(); return session; } } dao工厂为: package com.netBook.factory; import com.netBook.dao.userDao; import com.netBook.impl.userImpl; public class daoFactory { public static userDao getUserImpl(){ return new userImpl(); } } dao接口为: package com.netBook.dao; import java.util.List; import com.netBook.pojo.User; public interface userDao { // 判断是否会员 public boolean isUser(User user) throws Exception; } 实现为: package com.netBook.impl; import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import com.netBook.dao.userDao; import com.netBook.factory.sessionFactory; import com.netBook.pojo.User; public class userImpl implements userDao{ private Session session; public userImpl(){ this.session=sessionFactory.getSession(); } public boolean isUser(User user) throws Exception { boolean flag=false; String hql="FROM user AS u WHERE u.uerName=? AND u.password=?"; Query q=this.session.createQuery(hql); q.setString(0, user.getUserName()); q.setString(1, user.getPassword()); Iterator iter=q.list().iterator(); if(iter.hasNext()){ flag=true; } this.session.close(); return flag; } } 本人刚接触框架,是在看不出错在哪里?特此请教!只保留登录功能,数据库已经插入数据。如若有必要,将工程上传,请高手过目。

hibernate中类not mapped问题

spring项目中,用到hibernate mapping。后台写完之后junit test可以跑通,数据库可以存取数据,但是页面数据传过来之后,hql报错。已经仔细检查过hql中是查询的是类名还是表名以及各项配置,hpl中查询的是map过的类名。单元测试跑得通,所以xml配置应该也没错。但是页面存取数据的时候会报错。仔细检查过hql的大小写,全半角以及空格是否为中文空格,依然不能解决问题。希望各路高人给指条明路,感激不尽。。 报错内容:[code=text] Caused by: org.hibernate.hql.ast.QuerySyntaxException: User is not mapped [from User where userName=?] [/code] 具体的配置如下。 实体类:[code=java] package com.huatek.cloud.usercenter.entity; import com.huatek.framework.entity.FwAccount; public class User extends FwAccount{ private static final long serialVersionUID = 6736542524764495567L; private String seqNum; //数据的序列号,数据库中主键(id)。由于BaseServiceImpl中存在id字段,故重命名 private String userName; //用户名字段。如果注册方式为邮箱则它的值为email值;注册方式为手机则值为cellphone值 private String email; //用户的邮箱地址字段 private String cellphone; //用户的手机号字段 private int regType; //用户的注册类型字段 private String password; //用户的密码字段 private int activated; //用户的“是否激活”字段 private String validateCode; //用户的激活码字段 private java.sql.Timestamp registerTime; //用户的注册时间字段 //getter、setter方法略 } [/code] 类与表的映射文件:User.hbm.xml [code=text] import 实体类所在的package; <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package = "com.huatek.cloud.usercenter.entity"> <class name = "User" table="t_register"> <id name="seqNum" type="java.lang.String" column="id" length="100"></id> <property name="userName" column="name" type="java.lang.String" length="30"></property> <property name="email" column="email" type="java.lang.String" length="50"></property> <property name="cellphone" column="phone" type="java.lang.String" length="11"></property> <property name="regType" column="regType" type="java.lang.Integer" length="1"></property> <property name="password" column="password" type="java.lang.String" length="50"></property> <property name="activated" column="status" type="java.lang.Integer" length="1"></property> <property name="validateCode" column="validateCode" type="java.lang.String" length="100"></property> <property name="registerTime" column="registerTime" type="java.sql.Timestamp" length="100"></property> </class> </hibernate-mapping> [/code] 配置映射文件:application-base.xml [code=text] <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mappingLocations"> <list> <!-- base frame --> <value>classpath*:/com/huatek/framework/hibernate/maps/oracle/*.hbm.xml </value> <!-- data dictionary --> <value>classpath*:/com/huatek/dictionary/hibernate/oracle/*.hbm.xml </value> <!-- data authority --> <value>classpath*:/com/huatek/authority/hibernate/oracle/*.hbm.xml </value> <!-- cloud authority --> <value>classpath*:/com/huatek/cloud/usercenter/hibernate/mysql/*.hbm.xml </value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.generate_statistics">false</prop> <prop key="hibernate.default_batch_fetch_size">30</prop> </props> </property> <!-- <property name="lobHandler"> <ref local="oracleLobHandler" /> </property> --> <property name="eventListeners"> <map> <entry key="merge"> <bean class="org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener" /> </entry> </map> </property> </bean> [/code] 服务层中的实现方法,实际是就是判断userName是否已经存在库中以实现判断用户名重复: [code=java] @Override public boolean cmpUserName(int regType, String userName) { String hql = "from User where userName=?"; @SuppressWarnings("unchecked") List<User> resultUser = hibernateTemplate.find(hql,userName); //每次debug单步跟进到这里报错 if (resultUser.isEmpty()) return userNameNotDup; else return userNameDup; } [/code]

新手求解一个hibernate3.6.10的问题

先贴代码: User类: public class User { private Integer id; private String nickName; private String password; private String familyName; private String name; private String fullName; private Boolean gender; private String nameStyle; private Date registerDate; private Date lastLoginDate; // getters和setters省略 } User.hbm.xml映射文件: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="org.maxwell.app.domain"> <class name="User" table="users" lazy="true"> <id name="id" column="user_id" length="11" type="int" > <generator class="identity" /> </id> <property name="nickName" column="nick_name" length="20" unique="true" not-null="true" /> <property name="password" length="20" not-null="true" /> <property name="familyName" column="family_name" length="20" /> <property name="name" length="20" /> <property name="gender" type="java.lang.Boolean" /> <property name="nameStyle" column="name_style" type="string" length="1" /> <property name="registerDate" type="timestamp" column="register_date" /> <property name="lastLoginDate" type="timestamp" column="last_login_date" /> <property name="fullName" formula="( select concat(u.family_name, u.name) from users u where u.user_id= id)" /> </class> </hibernate-mapping> 测试类: public class TestNews { public static void main(String[] args) { Configuration config = new Configuration().configure(); SessionFactory sf = config.buildSessionFactory(); Session session = sf.openSession(); Transaction tx = session.beginTransaction(); User u = new User().setNickName("Maxwell").setPassword("1234") .setFamilyName("张").setName("飞扬").setNameStyle("E") .setRegisterDate(new Date()).setLastLoginDate(new Date()); session.save(u); System.out.println(u); User u2 = (User) session.load(User.class, new Integer(1)); System.out.println(u2); tx.commit(); session.close(); sf.close(); } } 请问为什么会报出下面这样的错误呢? Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not load an entity: [org.maxwell.app.domain.User#1] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.loader.Loader.loadEntity(Loader.java:2041) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86) at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76) at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3294) at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496) at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477) at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227) at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:147) at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090) at org.hibernate.impl.SessionImpl.immediateLoad(SessionImpl.java:1026) at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:176) at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215) at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190) at org.maxwell.app.domain.User_$$_javassist_0.getFullName(User_$$_javassist_0.java) at org.maxwell.app.domain.TestNews.main(TestNews.java:25) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'user0_.id' in 'where clause' at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:422) at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) at com.mysql.jdbc.Util.getInstance(Util.java:386) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4190) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4122) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2818) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2157) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2324) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) at org.hibernate.loader.Loader.getResultSet(Loader.java:1953) at org.hibernate.loader.Loader.doQuery(Loader.java:802) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274) at org.hibernate.loader.Loader.loadEntity(Loader.java:2037) ... 14 more

请教关于Hibernate的一个问题!

近来做毕业设计,使用hibernate和mysql数据库。在插入数据时出现如下问题: 异常1: [code="java"] com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index) values ('123', 4)' at line 1 [/code] 异常2: [code="java"] org.hibernate.exception.SQLGrammarException: could not insert: [qau.cookbook.hibernate.po.basedata.Foodkindctrl] [/code] 下面是我的数据库表的映射文件: [code="xml"] <hibernate-mapping> <class name="qau.cookbook.hibernate.po.basedata.Foodkindctrl" table="foodkindctrl" catalog="cookbook"> <id name="id" type="integer"> <column name="id" /> <generator class="identity" /> </id> <property name="foodkindctrlname" type="string"> <column name="foodkindctrlname" length="20" /> </property> <property name="index" type="integer"> <column name="index" /> </property> <set name="foodkinddtls" inverse="true"> <key> <column name="foodkindctrlid" /> </key> <one-to-many class="qau.cookbook.hibernate.po.basedata.Foodkinddtl" /> </set> </class> </hibernate-mapping> [/code] 下面是pojo类文件: [code="java"] public class Foodkindctrl implements java.io.Serializable { // Fields private Integer id; private String foodkindctrlname; private Integer index; private Set foodkinddtls = new HashSet(0); // Constructors /** default constructor */ public Foodkindctrl() { } /** full constructor */ public Foodkindctrl(String foodkindctrlname, Integer index, Set foodkinddtls) { this.foodkindctrlname = foodkindctrlname; this.index = index; this.foodkinddtls = foodkinddtls; } // Property accessors public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getFoodkindctrlname() { return this.foodkindctrlname; } public void setFoodkindctrlname(String foodkindctrlname) { this.foodkindctrlname = foodkindctrlname; } public Integer getIndex() { return this.index; } public void setIndex(Integer index) { this.index = index; } public Set getFoodkinddtls() { return this.foodkinddtls; } public void setFoodkinddtls(Set foodkinddtls) { this.foodkinddtls = foodkinddtls; } } [/code] 下面是我写的插入函数: [code="java"] public boolean saveKindCtrl(Foodkindctrl kindCtrl){ Transaction tx=null; try{ Session session = HibernateSessionFactory.getSession(); tx = session.beginTransaction(); session.save(kindCtrl); tx.commit(); log.debug("保存成功"); return true; }catch(Exception e){ e.printStackTrace(); log.debug("保存失败"); return false; }finally{ HibernateSessionFactory.closeSession(); } } [/code] 请问各位高手为什么会出现这样的问题,该如何解决呢?

at org.hibernate.exception.SQLStateConverter.handledNonSpecificException 错误!

在进行查询时出现的错误。 Criteria crit = session.createCriteria(getPersistentClass()); for (Criterion c : criterion) { crit.add(c); } return crit.list(); } 出现的主要异常如下: org.hibernate.exception.GenericJDBCException: could not initialize a collection: ×××.×××.caseVectorDetail#0000000B] [color=red]at org.hibernate.exception.[b]SQLStateConverter[/b].handledNonSpecificException[/color] ........................ [color=red]Caused by: java.sql.SQLException: Invalid value for getInt() - '0000002A' in column 2[/color] at com.mysql.jdbc.ResultSet.getIntFromString(ResultSet.java:2573) at com.mysql.jdbc.ResultSet.getNativeInt(ResultSet.java:7722) [color=red]比较怪异的是,如果我把CaseVecetor中的 多的一端由List改为Set,就一切正常,不知道为啥,急盼知道原因!!!!![/color] 类和相关的映射文件如下: public class CaseVector implements java.io.Serializable { private String caseVectorId; private String parameter; private Date trainDate; private boolean validate; private List<CaseVectorDetail> caseVectorDetail; .................. public class CaseVectorDetail { private String caseVectorDetailId; private CaseVector caseVector; private String svmVector; ........................ <hibernate-mapping > <class name="com.oneloong.sddes.biz.reason.vo.CaseVector" table="CaseVector" dynamic-update="true" dynamic-insert="true" > <id name="caseVectorId" column="caseVectorId" type="java.lang.String" length="32" > <generator class="com.oneloong.sddes.biz.utils.IncrementGenerator"> <!-- To add non XDoclet generator parameters, create a file named hibernate-generator-params-CaseVector.xml containing the additional parameters and place it in your merge dir. --> </generator> </id> <list name="caseVectorDetail" table="CaseVectorDetail" lazy="false" inverse="true" cascade="none" > <key column="caseVectorId" > </key> <index column="caseVectorDetailId" /> <one-to-many class="com.oneloong.sddes.biz.reason.vo.CaseVectorDetail" /> </list> <property name="trainDate" type="date" column="trainDate" /> <property name="validate" type="boolean" column="validate" /> <property name="parameter" type="string" column="parameter" length="2000" /> <!-- To add non XDoclet property mappings, create a file named hibernate-properties-CaseVector.xml containing the additional properties and place it in your merge dir. --> </class> </hibernate-mapping> <?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="com.oneloong.sddes.biz.reason.vo.CaseVectorDetail" table="CaseVectorDetail" dynamic-update="true" dynamic-insert="true" > <id name="caseVectorDetailId" column="caseVectorDetailId" type="java.lang.String" length="32" > <generator class="com.oneloong.sddes.biz.utils.IncrementGenerator"> <!-- To add non XDoclet generator parameters, create a file named hibernate-generator-params-CaseVectorDetail.xml containing the additional parameters and place it in your merge dir. --> </generator> </id> <many-to-one name="caseVector" class="com.oneloong.sddes.biz.reason.vo.CaseVector" cascade="none" outer-join="auto" column="caseVectorId" /> <property name="svmVector" type="string" column="svmVector" length="2000" /> <!-- To add non XDoclet property mappings, create a file named hibernate-properties-CaseVectorDetail.xml containing the additional properties and place it in your merge dir. --> </class> </hibernate-mapping>

hibernate 查詢字段(SET)為null 的數據

我想要某個對象下某個集合屬性為空的搜索結果,在寫hql語句的時候測試了N次一直不成功:select c from Category c where c.childCategory is null childCategory 是一個 集合,報 Caused by: java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use 錯誤 請問應該怎樣修改 [b]问题补充:[/b] 這是一個映射自身的類,為一對多 一個類別可以有多個子類別:childCategory 【code="java"] package com.bookseat.entitys; import java.util.HashSet; import java.util.Set; public class Category { private Integer categoryId; private String categoryName; public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } private Category fatherCategory; private Set<Category> childCategory = new HashSet<Category>(); private Set<Dishware> dishwaresByCategory = new HashSet<Dishware>(); public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public Set<Category> getChildCategory() { return childCategory; } public void setChildCategory(Set<Category> childCategory) { this.childCategory = childCategory; } public Set<Dishware> getDishwaresByCategory() { return dishwaresByCategory; } public void setDishwaresByCategory(Set<Dishware> dishwaresByCategory) { this.dishwaresByCategory = dishwaresByCategory; } public Category(String categoryName, Category fatherCategory, Set<Category> childCategory, Set<Dishware> dishwaresByCategory) { super(); this.categoryName = categoryName; this.fatherCategory = fatherCategory; this.childCategory = childCategory; this.dishwaresByCategory = dishwaresByCategory; } public Category getFatherCategory() { return fatherCategory; } public void setFatherCategory(Category fatherCategory) { this.fatherCategory = fatherCategory; } public Category() { } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((categoryId == null) ? 0 : categoryId.hashCode()); result = prime * result + ((categoryName == null) ? 0 : categoryName.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Category other = (Category) obj; if (categoryId == null) { if (other.categoryId != null) return false; } else if (!categoryId.equals(other.categoryId)) return false; if (categoryName == null) { if (other.categoryName != null) return false; } else if (!categoryName.equals(other.categoryName)) return false; return true; } } [/code] 配置文件: [code="xml"] <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.bookseat.entitys"> <class name="Category"> <id name="categoryId" column="category_id"> <generator class="increment" /> </id> <property name="categoryName" not-null="true" length="50" column="Category_Name" /> <set name="dishwaresByCategory" table="dishware_categorytable" cascade="save-update" lazy="false" > <key column="categoryId" /> <many-to-many column="dishwareId" class="Dishware" /> </set> <many-to-one name="fatherCategory" class="Category" fetch="select" cascade="save-update"> <column name="Category_parentId" /> </many-to-one> <set name="childCategory" inverse="true" lazy="false" cascade="save-update"> <key> <column name="Category_parentId" /> </key> <one-to-many class="Category" /> </set> </class> </hibernate-mapping> [/code] 按照yayg 兄的寫了搜索,不報錯但是仍然為空

晕死,有人见过类似的错误没?关于的hibernate的

我没分了 5......... 先来错误提示(首先说明不是简单的表不存在,所有的映射文件都没有映射过company表[至少没有显式引用]) [code="java"]ERROR 2009-09-10 13:31:58.343 JDBCExceptionReporter:logExceptions - Table 'bfw_utf8.company' doesn't exist org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: could not insert: [com.bafang.pojos.SiteAd]; bad SQL grammar [insert into site_ad (subsite_id, site_ad_location_id, site_ad_location_name, site_ad_keyword_id, site_ad_keyword, company_id, company_name, txt, url, media_type, media_file, type, charge, start_time, end_time, item_order, enabled) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]; nested exception is com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'bfw_utf8.company' doesn't exist Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'bfw_utf8.company' doesn't exist at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573) at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1160) at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:685) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1400) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1314) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1299) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105) at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248) at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298) at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519) at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:598) at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:358) at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:595) at com.bafang.pojos.base._BaseRootDAO.save(_BaseRootDAO.java:25) at com.bafang.pojos.base.BaseSiteAdDAO.save(BaseSiteAdDAO.java:20) at com.bafang.pojos.base.BaseSiteAdDAO$$FastClassByCGLIB$$33c630a7.invoke(<generated>) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:609) at com.bafang.pojos.dao.SiteAdDAO$$EnhancerByCGLIB$$29bf5095.save(<generated>) at com.bafang.web.action.admin.main.AdAction.add(AdAction.java:107) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:106) at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58) at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67) at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51) at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190) at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304) at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190) at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at com.bafang.web.servlet.BFActionServlet.process(BFActionServlet.java:26) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462) at javax.servlet.http.HttpServlet.service(HttpServlet.java:709) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at com.bafang.web.filters.HTMLFilter.synthesisURI(HTMLFilter.java:85) at com.bafang.web.filters.HTMLFilter.doFilter(HTMLFilter.java:60) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at com.bafang.web.filters.AdminFilter.doFilter(AdminFilter.java:41) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at com.bafang.web.filters.SubsiteFilter.doFilter(SubsiteFilter.java:35) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:118) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929) at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705) at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683) at java.lang.Thread.run(Thread.java:619)[/code] 相关hibernate映射文件 SiteAd.hbm.xml [code="xml"]<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping package="com.bafang.pojos"> <class name="SiteAd" table="site_ad"> <id name="id" type="integer" column="id"> <generator class="identity" /> </id> <property name="subsiteId" column="subsite_id" type="integer" not-null="false" length="11" /> <property name="siteAdLocationId" column="site_ad_location_id" type="string" not-null="false" length="50" /> <property name="siteAdLocationName" column="site_ad_location_name" type="string" not-null="false" length="255" /> <many-to-one name="siteAdLocation" column="site_ad_location_id" class="SiteAdLocation" not-null="false" insert="false" update="false" /> <property name="siteAdKeywordId" column="site_ad_keyword_id" type="integer" not-null="false" length="11" /> <property name="siteAdKeyword" column="site_ad_keyword" type="string" not-null="false" length="255" /> <property name="companyId" column="company_id" type="integer" not-null="false" length="11" /> <property name="companyName" column="company_name" type="string" not-null="false" length="255" /> <!--<many-to-one name="company" column="company_id" class="Store" not-null="false" insert="false" update="false" />--> <property name="txt" column="txt" type="string" not-null="false" length="255" /> <property name="url" column="url" type="string" not-null="false" length="255" /> <property name="mediaType" column="media_type" type="string" not-null="false" length="255" /> <property name="mediaFile" column="media_file" type="string" not-null="false" length="255" /> <property name="type" column="type" type="string" not-null="false" length="100" /> <property name="charge" column="charge" type="java.lang.Float" not-null="false" length="12" /> <property name="startTime" column="start_time" type="timestamp" not-null="false" length="19" /> <property name="endTime" column="end_time" type="timestamp" not-null="false" length="19" /> <property name="itemOrder" column="item_order" type="integer" not-null="false" length="11" /> <property name="enabled" column="enabled" type="boolean" not-null="false" length="1" /> </class> </hibernate-mapping>[/code] pojo相关类 com.bafang.pojos.SiteAd.java [code="java"]package com.bafang.pojos; import com.bafang.pojos.base.BaseSiteAd; public class SiteAd extends BaseSiteAd { private static final long serialVersionUID = 7092206885096359130L; public SiteAd () { } public String getTypeName(){ if("1".equals(getType())) return "多媒体广告"; else if("2".equals(getType())) return "连接广告"; else if("3".equals(getType())) return "店铺广告"; else if("4".equals(getType())) return "店铺评论广告"; else return "其它广告"; } }[/code] com.bafang.pojos.base.BaseSiteAd.java [code="java"]package com.bafang.pojos.base; import java.io.Serializable; public abstract class BaseSiteAd implements Serializable { protected Integer id; protected Integer subsiteId; protected String siteAdLocationId; protected String siteAdLocationName; protected Integer siteAdKeywordId; protected String siteAdKeyword; protected Integer companyId; protected String companyName; protected String txt; protected String url; protected String mediaType; protected String mediaFile; protected String type; protected Float charge; protected java.util.Date startTime; protected java.util.Date endTime; protected Integer itemOrder; protected Boolean enabled; protected com.bafang.pojos.SiteAdLocation siteAdLocation; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getSubsiteId() { return subsiteId; } public void setSubsiteId(Integer subsiteId) { this.subsiteId = subsiteId; } public String getSiteAdLocationId() { return siteAdLocationId; } public void setSiteAdLocationId(String siteAdLocationId) { this.siteAdLocationId = siteAdLocationId; } public String getSiteAdLocationName() { return siteAdLocationName; } public void setSiteAdLocationName(String siteAdLocationName) { this.siteAdLocationName = siteAdLocationName; } public Integer getSiteAdKeywordId() { return siteAdKeywordId; } public void setSiteAdKeywordId(Integer siteAdKeywordId) { this.siteAdKeywordId = siteAdKeywordId; } public String getSiteAdKeyword() { return siteAdKeyword; } public void setSiteAdKeyword(String siteAdKeyword) { this.siteAdKeyword = siteAdKeyword; } public Integer getCompanyId() { return companyId; } public void setCompanyId(Integer companyId) { this.companyId = companyId; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getTxt() { return txt; } public void setTxt(String txt) { this.txt = txt; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMediaType() { return mediaType; } public void setMediaType(String mediaType) { this.mediaType = mediaType; } public String getMediaFile() { return mediaFile; } public void setMediaFile(String mediaFile) { this.mediaFile = mediaFile; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Float getCharge() { return charge; } public void setCharge(Float charge) { this.charge = charge; } public java.util.Date getStartTime() { return startTime; } public void setStartTime(java.util.Date startTime) { this.startTime = startTime; } public java.util.Date getEndTime() { return endTime; } public void setEndTime(java.util.Date endTime) { this.endTime = endTime; } public Integer getItemOrder() { return itemOrder; } public void setItemOrder(Integer itemOrder) { this.itemOrder = itemOrder; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public com.bafang.pojos.SiteAdLocation getSiteAdLocation() { return siteAdLocation; } public void setSiteAdLocation(com.bafang.pojos.SiteAdLocation siteAdLocation) { this.siteAdLocation = siteAdLocation; } }[/code] 保存动作是直接调用spring的工具类 org.springframework.orm.hibernate3.support.HibernateDaoSupport.save(Object obj); 我debug过,就是保存的动作后报的错 数据库query 日志 [code="java"]090910 13:31:50 2 Query SET autocommit=0 2 Prepare select siteadloca0_.id as id17_, siteadloca0_.subsite_id as subsite2_17_, siteadloca0_.name as name17_, siteadloca0_.type as type17_, siteadloca0_.width as width17_, siteadloca0_.height as height17_, siteadloca0_.item_count as item7_17_, siteadloca0_.url as url17_, siteadloca0_.enabled as enabled17_ from site_ad_location siteadloca0_ where 1=1 and siteadloca0_.subsite_id=1 limit ? 2 Execute select siteadloca0_.id as id17_, siteadloca0_.subsite_id as subsite2_17_, siteadloca0_.name as name17_, siteadloca0_.type as type17_, siteadloca0_.width as width17_, siteadloca0_.height as height17_, siteadloca0_.item_count as item7_17_, siteadloca0_.url as url17_, siteadloca0_.enabled as enabled17_ from site_ad_location siteadloca0_ where 1=1 and siteadloca0_.subsite_id=1 limit 20 2 Close stmt 2 Query commit 2 Query SET autocommit=1 2 Query SET autocommit=0 2 Prepare select count(*) as col_0_0_ from site_ad_location siteadloca0_ where 1=1 and siteadloca0_.subsite_id=? 2 Execute select count(*) as col_0_0_ from site_ad_location siteadloca0_ where 1=1 and siteadloca0_.subsite_id=1 2 Close stmt 2 Query commit 2 Query SET autocommit=1 090910 13:31:58 2 Prepare insert into site_ad (subsite_id, site_ad_location_id, site_ad_location_name, site_ad_keyword_id, site_ad_keyword, company_id, company_name, txt, url, media_type, media_file, type, charge, start_time, end_time, item_order, enabled) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 2 Query select name into str from site_ad_location where id=new.site_ad_location_id 2 Query select name into str from company where id=new.company_id 2 Query SELECT 1 2 Close stmt D:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld, Version: 5.1.37-community-log (MySQL Community Server (GPL)). started with: TCP Port: 3306, Named Pipe: (null) Time Id Command Argument 090910 13:33:15 1 Connect root@localhost on 1 Query SET NAMES utf8 2 Connect root@localhost on 2 Query SELECT @@sql_mode 2 Query SET SESSION sql_mode='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' 2 Query SET NAMES utf8 2 Quit 090910 13:33:17 1 Quit 3 Connect root@localhost on 3 Query SELECT @@sql_mode 3 Query SET SESSION sql_mode='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' 3 Query SET NAMES utf8[/code] [b]问题补充:[/b] [quote]dwangel[/quote]已经清理过项目 还是一样 谢谢啊 已经找到问题了 以前写成的程序员 弄了个触发器在数据库里 刚刚发现的 谢谢了 分不多都给你了

Spring集成Hibernate,使用JPA注解方式,新增数据无法提交

<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>环境:</p> <p style="padding-left: 60px;">spring 3.1</p> <p style="padding-left: 60px;">hibernate 4.2.8 final </p> <p style="padding-left: 60px;">mysql 5.6</p> <p>问题描述:</p> <p style="padding-left: 30px;">调用controller的查询方法,可以正常返回数据</p> <p style="padding-left: 30px;">调用controller的创建方法,即:新增数据,控制台打印出了读取和修改序号表的sql,但是没有打印插入数据的sql,数据库表中也没有新增数据。</p> <p style="padding-left: 30px;">怀疑是spring控制的事务没有提交,但是排查了两三天,从网上找了各种方法,都没有解决问题。</p> <p style="padding-left: 30px;">请各位大侠拉小弟一把,实在是找不到事务为什么没有提交。</p> <p> </p> <p style="padding-left: 30px;">web.xml</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt; &lt;!-- 欢迎界面 --&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;!-- spring框架 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- 上下文配置 --&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt; /WEB-INF/applicationContext.xml, /WEB-INF/config/**/*.xml &lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- spring mvc --&gt; &lt;servlet&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;dispatcher&lt;/servlet-name&gt; &lt;!-- 拦截所有url --&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- 回话有效期30分钟 --&gt; &lt;session-config&gt; &lt;session-timeout&gt;30&lt;/session-timeout&gt; &lt;/session-config&gt; &lt;!-- log4j日志 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- log4j日志配置 --&gt; &lt;context-param&gt; &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/properties/log4j.properties&lt;/param-value&gt; &lt;/context-param&gt; &lt;/web-app&gt;</pre> <p> applicationContext.xml</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!-- 注解配置 --&gt; &lt;context:annotation-config /&gt; &lt;!--允许使用注解方式配置事务 --&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.lxl" /&gt; &lt;!-- 对标注@PersistenceContext的类经行增强,引入代理后的EntityManager实例 --&gt; &lt;bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /&gt; &lt;!-- 对标注@Repository的类经行增强,将EntityManager异常转换为SpringDAO体系的异常 --&gt; &lt;bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /&gt; &lt;!-- 属性文件 --&gt; &lt;context:property-placeholder location="/WEB-INF/properties/**/*.properties" /&gt; &lt;!-- 数据源 --&gt; &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt; &lt;property name="url" value="${jdbc.url}" /&gt; &lt;property name="username" value="${jdbc.username}" /&gt; &lt;property name="password" value="${jdbc.password}" /&gt; &lt;/bean&gt; &lt;!-- JPA 实体管理工厂 --&gt; &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&gt; &lt;property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" /&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="persistenceUnitName" value="ServicePlatform" /&gt; &lt;property name="jpaVendorAdapter"&gt; &lt;bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"&gt; &lt;property name="showSql" value="true" /&gt; &lt;property name="generateDdl" value="true" /&gt; &lt;property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" /&gt; &lt;/bean&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- JPA 事务管理 --&gt; &lt;bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <p> dispatcher-servlet.xml</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;!-- 默认的注解映射的支持 --&gt; &lt;mvc:annotation-driven /&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.lxl" /&gt; &lt;!-- 配置一下对json数据的转换 &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; &lt;property name="messageConverters"&gt; &lt;list&gt; &lt;bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"&gt;&lt;/bean&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; --&gt; &lt;!-- 视图解析器 --&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/view" /&gt; &lt;property name="suffix" value=".jsp" /&gt; &lt;/bean&gt; &lt;!-- 对静态资源文件的访问 方案一 (二选一) --&gt; &lt;mvc:default-servlet-handler /&gt; &lt;!-- 对静态资源文件的访问 方案二 (二选一) &lt;mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/&gt; &lt;mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/&gt; &lt;mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/&gt; --&gt; &lt;/beans&gt;</pre> <p> </p> <p> </p> <p style="padding-left: 30px;">persistence.xml</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"&gt; &lt;persistence-unit name="ServicePlatform" transaction-type="RESOURCE_LOCAL"&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">实体bean</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.entity; import java.io.Serializable; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "bd_id") public class Identity implements Serializable { private static final long serialVersionUID = -8763611811485844772L; @Id @GeneratedValue(strategy = GenerationType.TABLE) private Long id; @Column(length = 100) private String code; private Long value; @Column(length = 10) private String prefix; @Column(length = 10) private String suffix; @Column(length = 255) private String description; private Integer length; @Column(length = 30) private String creator; @Column(name = "create_date") private Timestamp createDate; @Column(length = 30) private String modifier; @Column(name = "modify_Date") private Timestamp modifyDate; private Boolean dr; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getLength() { return length; } public void setLength(Integer length) { this.length = length; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator; } public Timestamp getCreateDate() { return createDate; } public void setCreateDate(Timestamp createDate) { this.createDate = createDate; } public String getModifier() { return modifier; } public void setModifier(String modifier) { this.modifier = modifier; } public Timestamp getModifyDate() { return modifyDate; } public void setModifyDate(Timestamp modifyDate) { this.modifyDate = modifyDate; } public Boolean getDr() { return dr; } public void setDr(Boolean dr) { this.dr = dr; } @Override public String toString() { return "Identity [id=" + id + ", code=" + code + ", value=" + value + ", prefix=" + prefix + ", suffix=" + suffix + ", description=" + description + ", length=" + length + ", creator=" + creator + ", createDate=" + createDate + ", modifier=" + modifier + ", modifyDate=" + modifyDate + ", dr=" + dr + "]"; } } </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">IdentityDaoImpl.java</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.dao; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.lxl.bsp.api.exception.ServicePlatformException; import com.lxl.bsp.identity.entity.Identity; @Repository public class IdentityDaoImpl implements IIdentityDao { @PersistenceContext private EntityManager em; @Transactional(propagation = Propagation.REQUIRED) public Identity create(Identity data) { em.persist(data); return data; } @Override public Identity retriver(String id) throws ServicePlatformException { Long pk = Long.valueOf(id); return em.find(Identity.class, pk); } @Override public Identity update(Identity data) throws ServicePlatformException { em.persist(data); return data; } @Override public void delete(String id) throws ServicePlatformException { em.remove(retriver(id)); } } </pre> <p> IdentityController.java</p> <p> </p> <p style="padding-left: 30px;"> </p> <pre name="code" class="java">package com.lxl.bsp.identity.controller; import java.sql.Timestamp; import java.util.Calendar; import javax.annotation.Resource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.lxl.bsp.api.exception.ServicePlatformException; import com.lxl.bsp.identity.dao.IIdentityDao; import com.lxl.bsp.identity.entity.Identity; @Controller @RequestMapping("identity") public class IdentityController { private static Log log = LogFactory.getLog(IdentityController.class); @Resource private IIdentityDao dao; @RequestMapping("retriver") @ResponseBody public Identity retriver(@RequestParam String id) throws ServicePlatformException { return dao.retriver(id); } @RequestMapping("create") @ResponseBody public Identity create() throws ServicePlatformException { int i = 1; Identity data = new Identity(); data.setCode("code" + i); Calendar c = Calendar.getInstance(); data.setCreateDate(new Timestamp(c.getTime().getTime())); data.setCreator("creator" + i); data.setDescription("description" + i); data.setDr(false); // data.setId("id" + Integer.toString(i)); data.setLength(30); data.setModifier("modifier" + i); data.setModifyDate(new Timestamp(c.getTime().getTime())); data.setPrefix("prefix"); data.setSuffix("suffix"); data.setValue(0L); Identity returnData = dao.create(data); log.debug(returnData); return returnData; } @RequestMapping("update") @ResponseBody public Identity update() throws ServicePlatformException { int i = 1; Identity data = new Identity(); data.setCode("1"); Calendar c = Calendar.getInstance(); data.setCreateDate(new Timestamp(c.getTime().getTime())); data.setCreator("creator" + i); data.setDescription("description" + i); data.setDr(false); // data.setId("id" + Integer.toString(i)); data.setLength(30); data.setModifier("modifier" + i); data.setModifyDate(new Timestamp(c.getTime().getTime())); data.setPrefix("prefix"); data.setSuffix("suffix"); data.setValue(0L); Identity returnData = dao.update(data); log.debug(returnData); return returnData; } @RequestMapping("delete") public void delete(@RequestParam String id) throws ServicePlatformException { dao.delete(id); } } </pre> <p> </p> <p> </p> <p style="padding-left: 30px;">数据表结构DDL</p> <p style="padding-left: 30px;"> </p> <pre name="code" class="sql">-- ---------------------------- -- Table structure for bd_id -- ---------------------------- DROP TABLE IF EXISTS `bd_id`; CREATE TABLE `bd_id` ( `id` bigint(30) NOT NULL, `code` varchar(100) DEFAULT NULL, `create_date` datetime DEFAULT NULL, `creator` varchar(30) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `dr` tinyint(1) DEFAULT NULL, `length` int(11) DEFAULT NULL, `modifier` varchar(30) DEFAULT NULL, `modify_Date` datetime DEFAULT NULL, `prefix` varchar(10) DEFAULT NULL, `suffix` varchar(10) DEFAULT NULL, `value` bigint(20) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;</pre> <p> </p> <p> </p> <p style="padding-left: 30px;">附件中是项目压缩包,只要电脑上安装了数据库,解压即可运行,数据库名称是osd</p> <p> </p> </div>

getHibernateTemplate()为NUll,困扰好几天了,网上也找了好些方法一直解决不掉

小弟刚刚开始学SSH,是用的Struts2+Hibernate+Spring,运行的时候发现getHibernateTemplate()得到的模板类始终是nUll值,郁闷好几天了,一直在我网上试各种方法,迄今任为解决,恳请各位指教咯! [size=large][b]applicationContext.xml:([/b]事务处理这儿没贴出来)[/size] [code="java"] <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <!-- 定义数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/jjufriend"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <!-- 定义Hibernate的sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <!-- Hibernate 的sessionFactory的属性 --> <property name="hibernateProperties"> <props> <!-- 数据库方言 --> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <!-- 显示Hibernate持久化操作所生成的SQL语句 --> <prop key="hibernate.show_sql">true</prop> <!-- 将SQL脚本进行格式化后再输出 --> <prop key="hibernate.format_sql">true</prop> </props> </property> <!-- 列出全部的映射文件 --> <property name="mappingResources"> <list> <value>com/jjufriend/student/model/Student.hbm.xml</value></list> </property></bean> <!-- 配置dao组件 --> <bean id="studentDao" class="com.jjufriend.student.dao.impl.StudentDaoHibernate"> <!-- 依赖注入DAO组件所必需的SessionFactory引用 --> <property name="sessionFactory" ref="sessionFactory"> </property> </bean> <!-- 配置业务逻辑组件 --> <bean id="mgr" class="com.jjufriend.student.service.impl.StudentManagerImpl"> <property name="studentDao" ref="studentDao"></property> </bean> [/code] [size=large]studentDao.java:[/size] [code="java"]package com.jjufriend.student.dao; import java.util.List; import com.jjufriend.student.model.Student; public interface StudentDao { Student get(Integer id); Integer save(Student student); void update(Student student); void delete(Student student); void delete(Integer id); List<Student> findAll(); Student findStudentByNameAndPass(String username,String password); Student findByName(String username); }[/code] [size=large]StudentDaoHibernate.java:[/size] [code="java"]package com.jjufriend.student.dao.impl; import java.io.Serializable; import java.util.List; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.jjufriend.student.dao.StudentDao; import com.jjufriend.student.model.Student; public class StudentDaoHibernate extends HibernateDaoSupport implements StudentDao,Serializable { private SessionFactory sessionFactory; HibernateTemplate ht = this.getHibernateTemplate() ; public void delete(Student student) { // TODO Auto-generated method stub getHibernateTemplate().delete(student); } public void delete(Integer id) { // TODO Auto-generated method stub getHibernateTemplate().delete(get(id)); } public List<Student> findAll() { // TODO Auto-generated method stub return (List<Student>)getHibernateTemplate().find("from Student"); } public Student findByName(String username) { List stu = getHibernateTemplate().find("from Student st where st.username = ?",username); if(stu != null && stu.size() >= 1){ return (Student)stu.get(0); } return null; } public Student findStudentByNameAndPass(String username, String password) { // TODO Auto-generated method stub List students = null; try{ // HibernateTemplate temple = this.getHibernateTemplate(); System.out.println("模板类是否为NULL>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+ht); // 取出所有 students = temple.find("from student"); students = ht.find("from student st where st.username = " + username + " and st.password = " + password); }catch(Exception e){ System.out.println("查找过程中出现异常.............."); e.printStackTrace(); } if(students != null && students.size() >= 1){ return (Student)students.get(0); } return null; } public Student get(Integer id) { return (Student)getHibernateTemplate().get(Student.class, id); } public Integer save(Student student) { return (Integer)getHibernateTemplate().save(student); } public void update(Student student) { // TODO Auto-generated method stub getHibernateTemplate().update(student); } } [/code] [size=large]StudentManager.java:[/size] [code="java"]package com.jjufriend.student.service; import com.jjufriend.student.model.Student; public interface StudentManager { int addStudent(Student student) throws Exception; int loginValid(Student student) throws Exception; boolean validateName(String username) throws Exception; } [/code] [size=large]StudentManagerImpl.java:[/size] [code="java"]package com.jjufriend.student.service.impl; import com.jjufriend.student.dao.StudentDao; import com.jjufriend.student.dao.impl.StudentDaoHibernate; import com.jjufriend.student.model.Student; import com.jjufriend.student.service.StudentManager; public class StudentManagerImpl implements StudentManager { /*2009-11-12 22:44修改 出去new StudentDaoHibernate() */ private StudentDao studentDao = new StudentDaoHibernate() ; // private ApplicationContext cxt = // new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml"); // studentDao =(StudentDaoHibernate)cxt.getBean("studentDao"); public void setStudentDao(StudentDao studentDao){ this.studentDao = studentDao ; } public int addStudent(Student student) throws Exception { // TODO Auto-generated method stub try{ studentDao.save(student); return student.getId(); }catch(Exception e){ e.printStackTrace(); throw new Exception("新增用户时出现异常"); } } public int loginValid(Student student) throws Exception { try{ System.out.println(studentDao); System.out.println("是否取到页面提交的数据:Name="+student.getUsername()); Student stu = studentDao.findStudentByNameAndPass(student.getUsername(), student.getPassword()); if(stu != null ){ return stu.getId(); } }catch(Exception e){ System.out.println("验证用户登录时出现异常"); e.printStackTrace(); } // TODO Auto-generated method stub return -1; } public boolean validateName(String username) throws Exception { // TODO Auto-generated method stub try{ if (studentDao.findByName(username) != null){ return true ; } }catch(Exception e){ System.out.println("验证用户名是否用效时出错"); e.printStackTrace(); } return false ; } } [/code] 问题的关键是通过方法getHibernateTemplate()不能正确得到HibernateTemplate对象,始终的空值,网上有很多解决的办法,差不多我都试过了, 下面这种方法是说不能直接new StudentDao对象,用下面这种方法取得,可以启动服务器老是不停地跳动,一直不停,直到报错。 [code="java"] // private ApplicationContext cxt = // new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml"); // private StudentDao studentDao =(StudentDaoHibernate)cxt.getBean("studentDao");[/code] 还有些方法是直接从applicationContext.xml中的bean取得HibernateTemplate对象,始终都搞不定,望大家指教了。 [size=medium](顶格的System.out.println()语句均是测试用的语句)[/size] [b]问题补充:[/b] 谢谢大家的热心帮助!! 确实其中出了不少问题,主要是最近网上看到解决这个方法的帖子很多,尝试过很多方法,都有点儿改晕了。 一楼的方法我尝试了,还是不行,[code="java"] private ApplicationContext cxt = this.getApplicationContext(); private StudentDao studentDao = (StudentDaoHibernate)cxt.getBean("studentDao"); [/code] 其中那个this.getApplicationContext(); 方法根本不存在啊,无法取得配置文件。 之前类似的方法我也用过就是用[code="java"] private ApplicationContext cxt = new FileSystemXmlApplicationContext("../webapps/JJUFriend/WEB-INF/applicationContext.xml"); private StudentDao studentDao =(StudentDaoHibernate)cxt.getBean("studentDao"); [/code]取得,但是当启动服务器后,后台一直跑个不停,仿佛是个死循环似的。浏览器中通过http://localhost:8080访问都无效! StudentDaoHibernate.java中的private SessionFactory sessionFactory;已经去掉 数据库方言也该过来了

There is no Action mapped for namespace

使用的是J2EE+SHH框架, 具体代码如下: --- **struts.xml** ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="message" /> <constant name="struts.i18n.encoding" value="UTF-8" /> <!-- 指定Struts 2默认的ObjectFactory Bean - 交给Spring管理 --> <constant name="struts.objectFactory" value="spring" /> <!-- 开发者模式 --> <!-- <constant name="struts.devMode" value="true" /> --> <!-- 指定每次配置文件更改后,自动重新加载 --> <constant name="struts.configuration.xml.reload" value="false" /> </struts> ``` --- **applicationContext.xml** ``` **<?xml version="1.0" encoding="UTF-8"?> <!-- context是自动扫描和使用注解的上下文前缀;aop,tx是事物管理的前缀 -->** <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd" default-autowire="byName"> <!-- 采用自动扫描的方式查找bean(DAO,Service等等),多个用逗号隔开 --> <context:component-scan base-package="com.cheer.bookshop" /> <!-- 定时器任务 --> <task:annotation-driven /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <description>配置数据源</description> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/bookstore?useUnicode=true&amp;characterEncoding=UTF-8"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> <!-- 初始化连接数量 --> <property name="initialSize" value="1"/> <!-- 最大活动连接数量,一般等于数据库的最大并发数 --> <property name="maxActive" value="100"/> <!-- 最大空闲(等待)连接数量 --> <property name="maxIdle" value="-1"/> <!-- 最小空闲(等待)连接数量 --> <property name="minIdle" value="0"/> <!-- 获取连接时等待时间,超出将抛异常,单位毫秒 --> <property name="maxWait" value="10000"/> </bean> <!-- 配置hibernate session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <description>将数据源注入到sessionFactory,使用注解方式</description> <property name="dataSource" ref="dataSource"></property> <!-- 配置hibernate的一些属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.current_session_context_class">thread</prop> <prop key="hibernate.connection.release_mode">after_transaction</prop><!-- 释放session --> </props> </property> <!-- 自动扫描注解方式配置的hibernate映射文件(实体类) --> <property name="packagesToScan"> <list> <value>com.cheer.bookshop.Model</value> </list> </property> </bean> <!-- 定义事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <description> 增加事务管理</description> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 拦截器方式配置事务特性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 给business配置事务管理 --> <aop:config proxy-target-class="true"> <aop:pointcut id="allManagerMethod" expression="execution (* com.cheer.bookshop.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" /> </aop:config> </beans> ``` --- **JSP页面登陆Form表单** ``` <s:form action="userlogin.action" method="post"> <p><font color="red">&nbsp;&nbsp;&nbsp;${msg}</font></p> <div class="form_row"> <label class="contact"><strong>Username:</strong></label> <input type="text" class="contact_input" name="user.username" value="${user.username}"/> </div> <div class="form_row"> <label class="contact"><strong>Password:</strong></label> <input type="password" class="contact_input" name="user.password" value="${user.password}"/> </div> <div class="form_row"> <div class="terms"> <input type="checkbox" name="terms" /> Remember me </div> </div> <div class="form_row"> <input type="submit" class="register" value="login" /> </div> </s:form> ``` --- **Action类** ``` package com.cheer.bookshop.action; import java.io.IOException; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.Result; import com.cheer.bookshop.Model.User; import com.cheer.bookshop.service.impl.UserServiceImpl; import com.opensymphony.xwork2.ActionSupport; @Namespace("/") public class UserAction extends ActionSupport { @Resource private UserServiceImpl userServiceImpl; private User user; private String msg; //用户登录 @Action(value = "userlogin", results = {@Result(name = "success", location = "/index.jsp"), @Result(name = "input", location = "/jsp/user/myaccount.jsp", type = "redirect") }) public String login(){ User userdb = userServiceImpl.login(user.getUsername()); if(userdb != null){ String password = user.getPassword(); if(password.equals(userdb.getPassword())){ user=userdb; return SUCCESS; }else{ msg="密码错误,请重新输入!"; return INPUT; } }else{ msg="用户名不存在,请注册!"; return INPUT; } } //用户注册 @Action(value = "userregister", results = {@Result(name = "success", location = "/jsp/user/myaccount.jsp", type = "redirect") }) public String register(){ userServiceImpl.register(user); return SUCCESS; } //验证用户名是否已经被使用 @Action(value = "validateUsername") public String validateUsername() throws IOException{ HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=UTF-8"); String username = request.getParameter("username"); boolean flag = userServiceImpl.validateUsername(username); if(flag){ response.getWriter().println("<p><font color='red'>用户名已经存在</font></p>"); }else{ response.getWriter().println("<p><font color='green'>用户名可以使用</font></p>"); } return NONE; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } ``` --- 如上,Action有配置userlogin,登陆页form表单提交路径也是一样,单就是无法调整至aciton里,eclipse也没有报错,该如何解决? There is no Action mapped for namespace / and action name userlogin.

Spring注入action的Service为什么总是为空啊?

<p>话不多说,上代码:</p> <p>类Person,接口PersonDAO,接口PersonService略</p> <p>实现类PersonDAOImpl:</p> <pre name="code" class="java">package web.dao.impl; import java.util.List; import org.hibernate.LockMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import web.dao.PersonDAO; import web.entity.Person; /** * A data access object (DAO) providing persistence and search support for * Person entities. Transaction control of the save(), update() and delete() * operations can directly support Spring container-managed transactions or they * can be augmented to handle user-managed Spring transactions. Each of these * methods provides additional information for how to configure it for the * desired type of transaction control. * * @see web.entity.Person * @author MyEclipse Persistence Tools */ public class PersonDAOImpl extends HibernateDaoSupport implements PersonDAO { private static final Logger log = LoggerFactory.getLogger(PersonDAOImpl.class); // property constants public static final String PASSWORD = "password"; protected void initDao() { // do nothing } public void save(Person transientInstance) { log.debug("saving Person instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Person persistentInstance) { log.debug("deleting Person instance"); try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Person findById(java.lang.String id) { log.debug("getting Person instance with id: " + id); try { Person instance = (Person) getHibernateTemplate().get( "web.entity.Person", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Person instance) { log.debug("finding Person instance by example"); try { List results = getHibernateTemplate().findByExample(instance); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding Person instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Person as model where model." + propertyName + "= ?"; return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByPassword(Object password) { return findByProperty(PASSWORD, password); } public List findAll() { log.debug("finding all Person instances"); try { String queryString = "from Person"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public Person merge(Person detachedInstance) { log.debug("merging Person instance"); try { Person result = (Person) getHibernateTemplate().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Person instance) { log.debug("attaching dirty Person instance"); try { getHibernateTemplate().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Person instance) { log.debug("attaching clean Person instance"); try { getHibernateTemplate().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } }</pre> <p> </p> <p>这是myeclipse自己生成的也应该没有啥问题。</p> <p>PersonServiceImpl:</p> <pre name="code" class="java">package web.service.impl; import web.dao.PersonDAO; import web.entity.Person; import web.service.PersonService; public class PersonServiceImpl implements PersonService { private PersonDAO personDAO; public boolean equals(Object obj) { return personDAO.equals(obj); } public PersonDAO getPersonDAO() { return personDAO; } public void setPersonDAO(PersonDAO personDAO) { this.personDAO = personDAO; } public int hashCode() { return personDAO.hashCode(); } public String toString() { return personDAO.toString(); } @Override public void doSave(Person person) { personDAO.save(person); } } </pre> <p> </p> <p>PersonAction:</p> <pre name="code" class="java">package web.action; import web.entity.Person; import web.service.PersonService; import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial") public class PersonAction extends ActionSupport { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } private PersonService personService; public PersonService getPersonService() { return personService; } public void setPersonService(PersonService personService) { this.personService = personService; } public String doSave() { Person person = new Person(); person.setUsername(username); person.setPassword(password); System.out.println(PersonDAO);/////////////////////////////////////////////////////////////这里是NULL NULL NULL 调了一天 要疯了 personService.doSave(person); return SUCCESS; } } </pre> <p> </p> <p>applicationContext.xml:</p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt; &lt;property name="driverClassName"&gt; &lt;value&gt;com.mysql.jdbc.Driver&lt;/value&gt; &lt;/property&gt; &lt;property name="url"&gt; &lt;value&gt;jdbc:mysql://localhost:3306/test&lt;/value&gt; &lt;/property&gt; &lt;property name="username"&gt; &lt;value&gt;root&lt;/value&gt; &lt;/property&gt; &lt;property name="password"&gt; &lt;value&gt;1234&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt; &lt;!-- &lt;property name="configLocation" value="classpath:hibernate.cfg.xml"&gt; &lt;/property&gt; --&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;property name="mappingResources"&gt; &lt;list&gt; &lt;value&gt;web/dao/hibmap/Person.hbm.xml&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLInnoDBDialect&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.che.provider_class"&gt;org.hibernate.che.HashtableCheProvider&lt;/prop&gt; &lt;prop key="hibernate.query.ftory_class"&gt;org.hibernate.hql.classic.ClassicQueryTranslatorFtory&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;tx:advice id="txAdvice" transaction-manager="txManager"&gt; &lt;tx:attributes&gt; &lt;tx:method name="get*" read-only="true" propagation="SUPPORTS" /&gt; &lt;tx:method name="find*" read-only="true" propagation="SUPPORTS" /&gt; &lt;tx:method name="*" read-only="false" propagation="REQUIRED" /&gt; &lt;/tx:attributes&gt; &lt;/tx:advice&gt; &lt;aop:config&gt; &lt;aop:pointcut id="txDAO" expression="execution (* dao.*.*(..))" /&gt; &lt;aop:advisor pointcut-ref="txDAO" advice-ref="txAdvice" /&gt; &lt;/aop:config&gt; &lt;!-- DAOs --&gt; &lt;bean id="PersonDAOImpl" class="web.dao.impl.PersonDAOImpl" scope="singleton"&gt; &lt;property name="sessionFactory" ref="sessionFactory"/&gt; &lt;/bean&gt; &lt;!-- Services --&gt; &lt;bean id="PersonServiceImpl" class="web.service.impl.PersonServiceImpl" scope="prototype"&gt; &lt;property name="personDAO" ref="PersonDAOImpl"/&gt; &lt;/bean&gt; &lt;!-- Actions --&gt; &lt;bean name="PersonAction" class="web.action.PersonAction" scope="prototype"&gt; &lt;property name="personService" ref="PersonServiceImpl"/&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <p> </p> <p>web.xml:</p> <pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/classes/applicationContext.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;filter&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;filter-class&gt;org.apache.struts2.dispatcher.FilterDispatcher&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;url-pattern&gt;*.action&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;struts2&lt;/filter-name&gt; &lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt;</pre> <p>  struts.xml:</p> <pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"&gt; &lt;struts&gt; &lt;constant name="struts.objectFactory" value="spring"&gt;&lt;/constant&gt; &lt;package name="default" namespace="/" extends="struts-default"&gt; &lt;action name="PersonAction" class="web.action.PersonAction" method="doSave"&gt; &lt;result name="success"&gt;/success.jsp&lt;/result&gt; &lt;/action&gt; &lt;/package&gt; &lt;/struts&gt; </pre> <p> </p> <p>这是错误:</p> <p> </p> <pre>java.lang.NullPointerException web.action.PersonAction.doSave(PersonAction.java:42) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395) </pre> <p>我不明白我的spring配置文件没有找到什么映射错误,而且action中,service中都有注入类的set方法,可是为什么是null值,高手请指教,不胜感激!</p>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

Java基础知识面试题(2020最新版)

文章目录Java概述何为编程什么是Javajdk1.5之后的三大版本JVM、JRE和JDK的关系什么是跨平台性?原理是什么Java语言有哪些特点什么是字节码?采用字节码的最大好处是什么什么是Java程序的主类?应用程序和小程序的主类有何不同?Java应用程序与小程序之间有那些差别?Java和C++的区别Oracle JDK 和 OpenJDK 的对比基础语法数据类型Java有哪些数据类型switc...

我以为我学懂了数据结构,直到看了这个导图才发现,我错了

数据结构与算法思维导图

String s = new String(" a ") 到底产生几个对象?

老生常谈的一个梗,到2020了还在争论,你们一天天的,哎哎哎,我不是针对你一个,我是说在座的各位都是人才! 上图红色的这3个箭头,对于通过new产生一个字符串(”宜春”)时,会先去常量池中查找是否已经有了”宜春”对象,如果没有则在常量池中创建一个此字符串对象,然后堆中再创建一个常量池中此”宜春”对象的拷贝对象。 也就是说准确答案是产生了一个或两个对象,如果常量池中原来没有 ”宜春” ,就是两个。...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Linux面试题(2020最新版)

文章目录Linux 概述什么是LinuxUnix和Linux有什么区别?什么是 Linux 内核?Linux的基本组件是什么?Linux 的体系结构BASH和DOS之间的基本区别是什么?Linux 开机启动过程?Linux系统缺省的运行级别?Linux 使用的进程间通信方式?Linux 有哪些系统日志文件?Linux系统安装多个桌面环境有帮助吗?什么是交换空间?什么是root帐户什么是LILO?什...

Linux命令学习神器!命令看不懂直接给你解释!

大家都知道,Linux 系统有非常多的命令,而且每个命令又有非常多的用法,想要全部记住所有命令的所有用法,恐怕是一件不可能完成的任务。 一般情况下,我们学习一个命令时,要么直接百度去搜索它的用法,要么就直接用 man 命令去查看守冗长的帮助手册。这两个都可以实现我们的目标,但有没有更简便的方式呢? 答案是必须有的!今天给大家推荐一款有趣而实用学习神器 — kmdr,让你解锁 Linux 学习新姿势...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

史上最全的 python 基础知识汇总篇,没有比这再全面的了,建议收藏

网友们有福了,小编终于把基础篇的内容全部涉略了一遍,这是一篇关于基础知识的汇总的文章,请朋友们收下,不用客气,不过文章篇幅肯能会有点长,耐心阅读吧爬虫(七十)多进程multiproces...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

85后蒋凡:28岁实现财务自由、34岁成为阿里万亿电商帝国双掌门,他的人生底层逻辑是什么?...

蒋凡是何许人也? 2017年12月27日,在入职4年时间里,蒋凡开挂般坐上了淘宝总裁位置。 为此,时任阿里CEO张勇在任命书中力赞: 蒋凡加入阿里,始终保持创业者的冲劲,有敏锐的...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

新一代神器STM32CubeMonitor介绍、下载、安装和使用教程

关注、星标公众号,不错过精彩内容作者:黄工公众号:strongerHuang最近ST官网悄悄新上线了一款比较强大的工具:STM32CubeMonitor V1.0.0。经过我研究和使用之...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

大学一路走来,学习互联网全靠这几个网站,最终拿下了一把offer

大佬原来都是这样炼成的

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

什么时候跳槽,为什么离职,你想好了么?

都是出来打工的,多为自己着想

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你期望月薪4万,出门右拐,不送,这几个点,你也就是个初级的水平

先来看几个问题通过注解的方式注入依赖对象,介绍一下你知道的几种方式@Autowired和@Resource有何区别说一下@Autowired查找候选者的...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

程序员必知的 89 个操作系统核心概念

操作系统(Operating System,OS):是管理计算机硬件与软件资源的系统软件,同时也是计算机系统的内核与基石。操作系统需要处理管理与配置内存、决定系统资源供需的优先次序、控制输入与输出设备、操作网络与管理文件系统等基本事务。操作系统也提供一个让用户与系统交互的操作界面。 shell:它是一个程序,可从键盘获取命令并将其提供给操作系统以执行。 在过去,它是类似 Unix 的系统上...

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

立即提问
相关内容推荐