hibernate 采用session.save(Object)方法保存不了数据

代码如下:
bean类:
package org.hibernate.sample.modle;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;

/** @author Hibernate CodeGenerator */
public class Student implements Serializable {
private static final long serialVersionUID = 1L;

/** identifier field */
private Integer studentId;

/** persistent field */
private String name;

/** persistent field */
private String sex;

/** persistent field */
private Integer age;

/** full constructor */
public Student(String name, String sex, Integer age) {
    this.name = name;
    this.sex = sex;
    this.age = age;
}

/** default constructor */
public Student() {
}

public Integer getStudentId() {
    return this.studentId;
}

public void setStudentId(Integer studentId) {
    this.studentId = studentId;
}

public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}

public String getSex() {
    return this.sex;
}

public void setSex(String sex) {
    this.sex = sex;
}

public Integer getAge() {
    return this.age;
}

public void setAge(Integer age) {
    this.age = age;
}

public String toString() {
    return new ToStringBuilder(this)
        .append("studentId", getStudentId())
        .toString();
}

}
映射配置:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<id name="studentId" type="java.lang.Integer" column="student_id" unsaved-value="0">
    <generator class="native"/>
</id>

<property name="name" type="java.lang.String" column="name" not-null="true"
    length="45"/>
<property name="sex" type="java.lang.String" column="sex" not-null="true"
    length="45"/>
<property name="age" type="java.lang.Integer" column="age" not-null="true"
    length="45"/>

<!-- Associations -->



配置文件:
<?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">

<!-- SessionFactory 配置 -->
<session-factory>
    <!-- MySQL配置 -->

    <!-- 数据库URL -->
    <property name="connection.url">
        <![CDATA[ jdbc:mysql://localhost:3306/bms?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8]]>
    </property>
    <!-- 数据库JDBC驱动 -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <!--数据库用户名 -->
    <property name="connection.username"><![CDATA[root]]></property>
    <!--数据库用户密码 -->
    <property name="connection.password"></property>
    <!--dialect ,每个数据库都有其对应的Dialet以匹配其平台特性 -->
    <property name="dialect"> org.hibernate.dialect.MySQLDialect</property>
    <!-- 是否将运行期生成的SQL输出到日志以供调试 -->
    <property name="show_sql">true</property>
    <!--映射文件配置,注意配置文件名必须包含其相对于根的全路径 -->
    <mapping resource="org/hibernate/sample/modle/Student.hbm.xml"/>
</session-factory>  


测试类:
package test;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
import org.hibernate.sample.modle.Student;
import junit.framework.Assert;
import junit.framework.TestCase;

public class HibernateTest extends TestCase {
Session session = null;

/**
 * JUnit中setUp方法在TestCase初始化的时候会自动调用 一般用于初始化公用资源 此例中,用于初始化Hibernate Session
 */
protected void setUp() {
    try {
        /**
         * 采用hibernate.properties配置文件的初始化代码: Configuration config = new
         * Configuration(); config.addClass(TUser.class);
         */
        // 采用hibernate.cfg.xml配置文件
        // 请注意初始化Configuration时的差异:
        // 1.Configuration的初始化方式
        // 2.xml文件中已经定义了Mapping文件,因此无需再Hard Coding导入
        // POJO文件的定义
        Configuration config = new Configuration().configure();
        SessionFactory sessionFactory = config.buildSessionFactory();
        session = sessionFactory.openSession();
    } catch (HibernateException e) {
        e.printStackTrace();
    }
}

/**
 * 与setUp方法相对应,JUnit TestCase执行完毕时,会自动调用tearDown方法 一般用于资源释放
 * 此例中,用于关闭在setUp方法中打开的Hibernate Session
 */
protected void tearDown() {
    try {
        session.close();
    } catch (HibernateException e) {
        e.printStackTrace();
    }
}

/**
 * 对象持久化(Insert)测试方法
 * 
 * JUnit中,以”test”作为前缀的方法为测试方法,将被JUnit自动添加 到测试计划中运行
 */
public void testInsert() {
    try {
        Student student = new Student();

// student.setStudentId( Integer.valueOf(1));
student.setName("哈哈");
student.setSex("男");
student.setAge(Integer.valueOf(13));
session.save(student);
session.flush();
System.out.println(student.getStudentId());
} catch (HibernateException e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}

/**
 * 对象读取(Select)测试 请保证运行之前数据库中已经存在name=’Erica’的记录
 */
public void testSelect() {
    String hql = " from Student where name='哈哈'";
    try {
        Query query= session.createQuery(hql);
        List list=query.list();
        Student student = (Student) list.get(0);
        Assert.assertEquals(student.getName(), "哈哈");
    } catch (HibernateException e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
}

}

[b]问题补充:[/b]
数据库表的
create table student(
student_id integer unsigned auto_increment,
name varchar(45) not null,
sex varchar(45) not null,
age integer not null

);

2个回答

没有将你的save方法放在事务中!
[code="java"]Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.save(...);
tx.commit();
session.close();[/code]
另请参见robbin的精华贴:http://www.iteye.com/post/806

[size=medium]是不是save方法中的Object的属性不全啊?
库没问题吗?
先手动插一条数据试试,看看是不是库的问题[/size]

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
关于hibernate的session.saveOrUpdate()底层实现的问题
这个问题会有点模糊,因为我的目的是想知道 session的增删改查底层实现原理,所以我详细看了下(以saveOrUpdate()方法为主)saveOrUpdate的流程,它的底层相当的庞大,我很认真的看源码,但是其中有很大一部分我都看不懂,我想知道从session.saveOrUpdate(Object javaBean)此方法开始到结束,那个作者是怎么想出来的,那么多的成员变量和局部变量,都是用在哪里的,要怎么看hibernate的源码? Session.saveOrUpdate()目的是为了 新增或者更新 ---执行sql语句 insert或者update 但是insert 或update是自动生成所以要有org.hibernate.sql包来生成sql,还有事物的设置, 但是我能想到的做一个hibernate的需求就这么多了,可是源码中的变量和类多的都不敢想象,我在想它们都用在那个流程,起到什么作用,真是没有办法啦、啊啊啊啊啊啊 最好-->能够给我提供一些好的书本或者文章(专门针对hibernate底层框架<其他的框架spring、struts2也要>的书或者文章),我在网上完全搜不到hibernate的底层的知识,根本就没有半个人写过关于hibernate底层的东西,我渴望了解它的底层,希望有IT界的朋友帮帮忙,我会感激不尽,真的、谢谢
org.hibernate.TransientObjectException
[code]javax.servlet.ServletException: org.springframework.dao.InvalidDataAccessApiUsageException: com.entity.User; nested exception is org.hibernate.TransientObjectException: com.entity.User org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:535) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:433) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) javax.servlet.http.HttpServlet.service(HttpServlet.java:710) javax.servlet.http.HttpServlet.service(HttpServlet.java:803) com.util.FilterClass.doFilter(FilterClass.java:24) root cause org.springframework.dao.InvalidDataAccessApiUsageException: com.entity.User; nested exception is org.hibernate.TransientObjectException: com.entity.User org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:633) org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412) org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:377) org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:338) com.dao.daoimpl.BodycheckDaoImpl.adduserinfo(BodycheckDaoImpl.java:42) com.delegate.delegateimpl.BodycheckdelegateImpl.adduserinfo(BodycheckdelegateImpl.java:24) com.web.struts.action.BodyCheckAction.adduserinfo(BodyCheckAction.java:69) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) java.lang.reflect.Method.invoke(Unknown Source) org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270) org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) javax.servlet.http.HttpServlet.service(HttpServlet.java:710) javax.servlet.http.HttpServlet.service(HttpServlet.java:803) com.util.FilterClass.doFilter(FilterClass.java:24) root cause org.hibernate.TransientObjectException: com.entity.User org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:216) org.hibernate.type.EntityType.getIdentifier(EntityType.java:108) org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:221) org.hibernate.type.TypeFactory.findDirty(TypeFactory.java:476) org.hibernate.persister.entity.AbstractEntityPersister.findDirty(AbstractEntityPersister.java:2803) org.hibernate.event.def.DefaultFlushEntityEventListener.dirtyCheck(DefaultFlushEntityEventListener.java:467) org.hibernate.event.def.DefaultFlushEntityEventListener.isUpdateNecessary(DefaultFlushEntityEventListener.java:190) org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:113) org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:195) org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:76) org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26) org.hibernate.impl.SessionImpl.flush(SessionImpl.java:985) org.springframework.orm.hibernate3.HibernateAccessor.flushIfNecessary(HibernateAccessor.java:390) org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:373) org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:338) com.dao.daoimpl.BodycheckDaoImpl.adduserinfo(BodycheckDaoImpl.java:42) com.delegate.delegateimpl.BodycheckdelegateImpl.adduserinfo(BodycheckdelegateImpl.java:24) com.web.struts.action.BodyCheckAction.adduserinfo(BodyCheckAction.java:69) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) java.lang.reflect.Method.invoke(Unknown Source) org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270) org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196) org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) javax.servlet.http.HttpServlet.service(HttpServlet.java:710) javax.servlet.http.HttpServlet.service(HttpServlet.java:803) com.util.FilterClass.doFilter(FilterClass.java:24) [/code] 帮我看看呢 我是用spring管理Hibernian和struts的 是建立有关系的 [code] public Integer adduserinfo(final Userinfo userinfo) { Integer num=(Integer)this.getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session s)throws HibernateException,SQLException { return s.save(userinfo); } }); [/code] userinfo包含有user的信息。 我看了意思就是 userinfo 中的user 是transient状态的, 不知道该怎么解决 [b]问题补充:[/b] userinfo配置的是多对一, 只在userinfo中配置了private User user; user中没有关联userinfo [b]问题补充:[/b] 知道怎么回事了 update userinfo 之前 执行了[color=red]userinfo.setUser(new User()),[/color]此时的userinfo是persistent状态,而user属性是一个transient状态的对象,并且cascade为默认的"none"(如果是all那么会试图创建一个新的User对象),所以无法更新userinfo。 都是 spring 的 formbackingObject 惹的麻烦,害我debuge了一下午,希望大家不要再范类似错误了。
hibernate一对一关联关系映射的问题
[color=red]定义一个人的域对象:[/color] [code="java"]public class Person { private int id; private String name; private IdCard idCard; }[/code] [color=red]定义一个该人的身份证的域对象:[/color] [code="java"]public class IdCard { private int id; private Date usefuldate; private Person person; }[/code] [color=red]Person.hbm.xml配置文件:[/color] [code="java"]<hibernate-mapping package="com.aaasoft.domain"> <class name="Person" table="person"> <id name="id" column="id"> <generator class="sequence"> <param name="sequence">PERSON_SEQUENCE</param> </generator> </id> <property name="name" column="name"/> <one-to-one name="idCard"></one-to-one> </class> </hibernate-mapping>[/code] [color=red]IdCard.hbm.xml配置文件:[/color] [code="java"]<hibernate-mapping package="com.aaasoft.domain"> <class name="IdCard" table="idcard"> <id name="id" column="id"> <generator class="foreign"> <param name="property">person</param> </generator> </id> <property name="usefuldate" column="usefuldate" /> <one-to-one name="person"></one-to-one> </class> </hibernate-mapping>[/code] 工具类里的保存方法: [code="java"] public static void save(Object entity) { Session session = null; Transaction tx = null; try { session = HibernateUtil.getSession(); tx = session.beginTransaction(); session.save(entity); tx.commit(); } finally { if (session != null) session.close(); } }[/code] 测试方法: [code="java"] public static void main(String[] args) { Person p = new Person(); p.setName("idcard test"); IdCard idCard = new IdCard(); p.setIdCard(idCard); idCard.setUsefuldate(new Date()); idCard.setPerson(p); PersonDao persondao = new PersonDaoImpl(); persondao.savePerson(p); IdCardDao idcarddao = new IdCardDaoImpl(); idcarddao.addIdCard(idCard); }[/code] 异常信息: [code="java"]Hibernate: select PERSON_SEQUENCE.nextval from dual Hibernate: insert into person (name, id) values (?, ?) Hibernate: insert into idcard (usefuldate, id) values (?, ?) Exception in thread "main" org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:253) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:237) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) at com.atwasoft.utils.HibernateUtil.save(HibernateUtil.java:37) at com.atwasoft.dao.impl.IdCardDaoImpl.addIdCard(IdCardDaoImpl.java:10) at com.atwasoft.test.Test.main(Test.java:30) Caused by: java.sql.BatchUpdateException: ORA-02291: 违反完整约束条件 (TEST.IDCARD_FK) - 未找到父项关键字 at oracle.jdbc.driver.DatabaseError.throwBatchUpdateException(DatabaseError.java:342) at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10656) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)[/code] [color=red][size=medium]数据库里的idcard表的ID既做主键,又做外键(参考Person的主键ID),怎么还是报找不到父项关键字呢[/size][/color]
save the transient instance before flushing:
SSH开发save()报错: 严重: Exception occurred during processing request: object references an unsaved transient instance - save the transient instance before flushing: com.resume.demain.Resume org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.resume.demain.Resume at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:279) at org.hibernate.type.EntityType.getIdentifier(EntityType.java:455) at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:281) at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:291) at org.hibernate.type.TypeHelper.findDirty(TypeHelper.java:296) at org.hibernate.persister.entity.AbstractEntityPersister.findDirty(AbstractEntityPersister.java:4079) at org.hibernate.event.internal.DefaultFlushEntityEventListener.dirtyCheck(DefaultFlushEntityEventListener.java:532) at org.hibernate.event.internal.DefaultFlushEntityEventListener.isUpdateNecessary(DefaultFlushEntityEventListener.java:215) at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:142) at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:216) at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:85) at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:38) at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1224) at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:464) at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:2905) at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2281) at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:230) at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65) at com.resume.dao.impl.ResumeDaoImpl.save(ResumeDaoImpl.java:28) at com.resume.service.impl.ResumeServiceImpl.save(ResumeServiceImpl.java:25) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) 前台jsp页面,动态添加: <script type="text/javascript" src="js/jquery-1.8.0.js"></script> <script type="text/javascript"> $(function() { $("#btnAddeducation").click( function() { var num = $("#educationhidNum").val(); num = parseInt(num); num++; $("#educationhidNum").val(num); $("#edcationaddtable").clone(true).attr("id", "edcationaddtable" + num).appendTo("#educationbackgrroundadd"); //clone $("#edcationaddtable" + num).each(function() { $(this).find("input[type='text']").val(""); $(this).find("input[name='educationBackgroundlist[0].startTime']").attr("id","educationStartTime"+ num).attr("name","educationBackgroundlist["+ num+"].startTime"); $(this).find("input[name='educationBackgroundlist[0].university']").attr("id","university"+ num).attr("name","educationBackgroundlist["+ num+"].university"); $(this).find("input[name='educationBackgroundlist[0].overTime']").attr("id","educationOverTime"+ num).attr("name","educationBackgroundlist["+ num+"].overTime"); $(this).find("input[name='educationBackgroundlist[0].professional']").attr("id","professional"+ num).attr("name","educationBackgroundlist["+ num+"].professional"); $(this).find("input[name='educationBackgroundlist[0].qualification']").attr("id","qualification"+ num).attr("name","educationBackgroundlist["+ num+"].qualification"); $(this).find("input[name='deletenum']").attr("class","edcationdeletetable"+ num).attr("name","deletenum"+ num).attr("onclick","deletethiseducation('"+num+"')"); }); }); }); </script> <script type="text/javascript"> function deletethiseducation(a){ a = parseInt(a); if(a==0){ alert("该项不能删除!"); return; } document.getElementById("edcationaddtable"+a).remove(); } </script> <div id="educationbackgrroundadd"> <table id = "edcationaddtable"> <tr> <td colspan="4" style="font-weight:bold; font-size:20px;">教育背景:</td> </tr> <tr> <td>开始&nbsp;时间:<input type="text" name="educationBackgroundlist[0].startTime" id="educationStartTime" /></td> <td ></td> <td >学&nbsp;&nbsp;&nbsp;校:<input type="text" name="educationBackgroundlist[0].university" id="university" /></td> <td ></td> </tr> <tr> <td>结束&nbsp;时间:<input type="text" name="educationBackgroundlist[0].overTime" id="educationOverTime" /></td> <td></td> <td>专&nbsp;&nbsp;&nbsp;业:<input type="text" name="educationBackgroundlist[0].professional" id="professional" /></td> <td></td> </tr> <tr> <td>学&nbsp;&nbsp;&nbsp;位:<input type="text" name="educationBackgroundlist[0].qualification" id="qualification" /></td> <td></td> <td> </td> <td><input type="button" name="deletenum" class="edcationdeletetable" value="点击删除" onclick="deletethiseducation('0')" /></td> </tr> </table> <table> <tr> <td></td> <td></td> <td></td> <td> <input id="educationhidNum" type="hidden" name="hidNum" value="0" /> <input type="button" style="margin-left:100%;" value="继续添加" id="btnAddeducation" onmouseover="this.style.backgroundColor='red';" onmouseout="this.style.backgroundColor='#d4e3e5';" /> </td> </tr> </table> 后台Action: private List<EducationBackground> educationBackgroundlist = new ArrayList<EducationBackground>(); public Resume backresume() throws Exception { List<EducationBackground> educationBackgroundlist1 = this.educationBackgroundlist(); Resume resume = new Resume(); resume.setResumeID(resumeID); resume.setApartment(apartment); resume.setAppliedPosition(appliedPosition); resume.setDestination(destination); resume.setEducationBackground(educationBackgroundlist1); resume.setEmail(email); resume.setEvaluation(evaluation); resume.setExpectation(expectation); resume.setFamilySituation(familySituation); resume.setLanguageProficiency(languageProficiency); resume.setMotivation(motivation); resume.setNationality(nationality); resume.setOperatingTime(operatingTime); resume.setOperator(operator); resume.setOther(other); resume.setPersonalAge(personalAge); resume.setPersonalName(personalName); resume.setPersonalSex(personalSex); resume.setPhoneNum(phoneNum); resume.setResumeState(resumeState); resume.setSourceCompany(sourceCompany); resume.setWorkSeniority(workSeniority); return resume; } public String addresume() throws Exception { Resume resume = this.backresume(); resumeService.save(resume); Pageres pageres = this.pageser(); list = resumeService.queryresumelist(resume,pageres,workSeniority1,workSeniority2,pageNo,pageSize); return SUCCESS; } Resume简历为主表,EducationBackground为简历从表教育背景表,两个表都有主外键关系, @OneToMany(fetch = FetchType.EAGER,targetEntity=EducationBackground.class,cascade={CascadeType.ALL},orphanRemoval=true) // @Cascade(value={org.hibernate.annotations.CascadeType.ALL}) // @NotFound(action = NotFoundAction.IGNORE) @JoinColumn(name="resume_id") public List<EducationBackground> getEducationBackground() { return educationBackground; } public void setEducationBackground(List<EducationBackground> educationBackground) { this.educationBackground = educationBackground; } @ManyToOne(targetEntity=Resume.class,fetch = FetchType.EAGER) @JoinColumn(name="resume_id",referencedColumnName="resumeID", insertable=true, updatable=true) public Resume getResume() { return resume; } public void setResume(Resume resume) { this.resume = resume; } 数据访问层的sava()方法; @Override public void save(Resume resume) { Session session = sessionFactory.openSession(); //Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); //session.persist(resume); //session.save(resume); session.persist(resume); tx.commit(); session.close(); } 当我在action中手动添加教育背景的数据时,数据为多条,可以插入数据库,但是我换成jsp动态添加时 就报上面的错误,是怎么回事啊 ?? 求大神帮帮忙,万分感谢!
CGLIB实现的一个hibernate事务管理代理类出现的问题,以及一些疑问
先声明下,本人系菜鸟一个,问的问题如果类似于1+1为什么等于2,请少拍板 <br />这2天在学习CGLIB,一时兴起用CGLIB实现了一个管理hibernate事务的类。 <br />代码如下:<pre name="code" class="java">package com.test; import java.lang.reflect.Method; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import com.linbs.core.common.hibernate.HibernateUtil; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; /** * 使用CGLIB进行事务处理设置 * @author linbs */ public class TransactionDAOProxy implements MethodInterceptor { private static Log logger = LogFactory.getLog(TransactionDAOProxy.class); private Enhancer enhancer=new Enhancer(); public Object getDAO(Class clz){ enhancer.setSuperclass(clz); enhancer.setCallback(this); return enhancer.create(); } public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { Session session = null; Transaction tx = null; Object result = null; try{ session = HibernateUtil.getSession(); tx = session.beginTransaction(); result = proxy.invokeSuper(obj, args); tx.commit(); session.flush(); }catch(HibernateException e){ try { tx.rollback(); } catch (HibernateException e1) { logger.error(e1.getMessage()); throw e; } }finally{ try { HibernateUtil.closeSession(); } catch (HibernateException e) { logger.error(e.getMessage()); throw new Throwable("关闭session时出错!"); } } return result; } } </pre> <br /> <br />其中的HibernateUtil类的getSession()方法是一个从线程中取得session副本的函数,代码相信各位大牛已经很熟悉,在此就不贴出来了。 <br /> <br />测试类如下: <br /><pre name="code" class="java">package com.test; import com.linbs.core.common.hibernate.BaseHibernateDAO; import com.linbs.usermanage.model.User; public class Test { public static void main(String[] args){ TransactionDAOProxy proxy = new TransactionDAOProxy(); BaseHibernateDAO baseDAO = (BaseHibernateDAO)proxy.getDAO(BaseHibernateDAO.class); User user = new User(); user.setUserName("abcProxy"); user.setUserPwd("abcProxy"); user.setEmail("abc@126.cn"); baseDAO.save(user); } } </pre> <br /> <br />其中的baseDAO.save(user);函数代码如下: <br /><pre name="code" class="java">/** * 取得当期进程的session对象 * @return */ public Session getSession() { return HibernateUtil.getSession(); } /** * 保存一个新的实体类的实例,并返回标识号 * @param obj * @return */ public Serializable save(final Object obj) { return this.getSession().save(obj); } </pre> <br /> <br /> <br />测试类运行的时候报出了如下错误: <br />Exception in thread "main" org.hibernate.SessionException: Session is closed! <br /> at org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:49) <br /> at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:526) <br /> at org.hibernate.impl.SessionImpl.save(SessionImpl.java:518) <br /> at org.hibernate.impl.SessionImpl.save(SessionImpl.java:514) <br /> at com.linbs.core.common.hibernate.BaseHibernateDAO.save(BaseHibernateDAO.java:31) <br /> at com.linbs.core.common.hibernate.BaseHibernateDAO$$EnhancerByCGLIB$$c88d447e.CGLIB$save$3(&lt;generated&gt;) <br /> at com.linbs.core.common.hibernate.BaseHibernateDAO$$EnhancerByCGLIB$$c88d447e$$FastClassByCGLIB$$e5947bbb.invoke(&lt;generated&gt;) <br /> at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:167) <br /> at com.test.TransactionDAOProxy.intercept(TransactionDAOProxy.java:49) <br /> at com.linbs.core.common.hibernate.BaseHibernateDAO$$EnhancerByCGLIB$$c88d447e.save(&lt;generated&gt;) <br /> at com.test.Test.main(Test.java:21) <br /> <br /> <br />通过debug发现session = HibernateUtil.getSession();和result = proxy.invokeSuper(obj, args);中调用的session不属于同一个对象。而session是在线程中取得的,可见session = HibernateUtil.getSession();和result = proxy.invokeSuper(obj, args);不是在同一个线程中运行的。于是猜想:cglib在运行中动态创建类而新创建的类和原来创建的类是不在同一线程中运行的,不知道我的猜想是不是正确,请各位大牛指教!!
JPA 实现修改的时候有问题(Could not execute JDBC batch updat)
我先从数据库查一条记录,修改的时候调用以下save方法 public String save() { if (StringUtils.isNotBlank(this.id)) { this.model = (T) this.manager.get(this.id); } if (null != this.model) { this.model = (T) this.manager.save(this.model); this.addActionMessage("save entity sucessfully!"); } else { this.addActionError("entity to save is null!"); return Action.INPUT; } return Action.SUCCESS; } [color=red]后台报错[/color] 56828 [http-8080-1] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000 56828 [http-8080-1] ERROR org.hibernate.util.JDBCExceptionReporter - Duplicate entry '2009062316522976530' for key 'PRIMARY' 56828 [http-8080-1] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) [b]问题补充:[/b] [color=red]save调用这个方法[/color] public T save(T object) { Assert.notNull(object, "entity不能为空"); if (null == object.getId()) { object.setId(String.valueOf(PKgen.getInstance().nextPK())); } return this.jpaTemplate.merge(object); } [b]问题补充:[/b] 118235 [http-8080-6] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000 118235 [http-8080-6] ERROR org.hibernate.util.JDBCExceptionReporter - Duplicate entry '2009062316522976530' for key 'PRIMARY' 118235 [http-8080-6] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137) at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:54) at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:456) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:732) at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:701) at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:321) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:116) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at $Proxy22.save(Unknown Source) at com.ruling.base.web.struts2.action.BaseCRUDAction.save(BaseCRUDAction.java:64) 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 com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:112) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) Caused by: java.sql.BatchUpdateException: Duplicate entry '2009062316522976530' for key 'PRIMARY' at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1666) at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1082) at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297) at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268) ... 85 more [ERROR] 2009-06-23 18:59:55,687 [freemarker.log.Log4JLoggerFactory$Log4JLogger.error(Log4JLoggerFactory.java:96)] Method public java.lang.String org.hibernate.exception.NestableRuntimeException.getMessage(int) threw an exception when invoked on org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update The problematic instruction: ---------- ==> ${msg[0]} [on line 68, column 29 in org/apache/struts2/dispatcher/error.ftl] ---------- Java backtrace for programmers: ---------- freemarker.template.TemplateModelException: Method public java.lang.String org.hibernate.exception.NestableRuntimeException.getMessage(int) threw an exception when invoked on org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at freemarker.ext.beans.SimpleMethodModel.exec(SimpleMethodModel.java:136) at freemarker.ext.beans.SimpleMethodModel.get(SimpleMethodModel.java:146) at freemarker.core.DynamicKeyName.dealWithNumericalKey(DynamicKeyName.java:111) at freemarker.core.DynamicKeyName._getAsTemplateModel(DynamicKeyName.java:90) at freemarker.core.Expression.getAsTemplateModel(Expression.java:89) at freemarker.core.Expression.getStringValue(Expression.java:93) at freemarker.core.DollarVariable.accept(DollarVariable.java:76) at freemarker.core.Environment.visit(Environment.java:196) at freemarker.core.MixedContent.accept(MixedContent.java:92) at freemarker.core.Environment.visit(Environment.java:196) at freemarker.core.IfBlock.accept(IfBlock.java:82) at freemarker.core.Environment.visit(Environment.java:196) at freemarker.core.IteratorBlock$Context.runLoop(IteratorBlock.java:172) at freemarker.core.Environment.visit(Environment.java:351) at freemarker.core.IteratorBlock.accept(IteratorBlock.java:95) at freemarker.core.Environment.visit(Environment.java:196) at freemarker.core.MixedContent.accept(MixedContent.java:92) at freemarker.core.Environment.visit(Environment.java:196) at freemarker.core.IfBlock.accept(IfBlock.java:82) at freemarker.core.Environment.visit(Environment.java:196) at freemarker.core.MixedContent.accept(MixedContent.java:92) at freemarker.core.Environment.visit(Environment.java:196) at freemarker.core.Environment.process(Environment.java:176) at freemarker.template.Template.process(Template.java:232) at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:703) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:112) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) Caused by: java.lang.NullPointerException at freemarker.ext.beans.BeansWrapper.unwrapArguments(BeansWrapper.java:573) at freemarker.ext.beans.SimpleMethodModel.exec(SimpleMethodModel.java:109) ... 42 more 2009-6-23 18:59:55 org.apache.catalina.core.StandardWrapperValve invoke 严重: Servlet.service() for servlet default threw exception java.lang.IllegalStateException at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:407) at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:707) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:485) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:395) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:112) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) [b]问题补充:[/b] if (StringUtils.isNotBlank(this.id)) { this.model = (T) this.manager.get(this.id); } [color=red]这里我已删除了,才报错[/color] [b]问题补充:[/b] ywbanm: [color=red]我是先get出来 在修改属性 再merge [/color] 后台老是报这个错误::::::::: [color=red]WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000 783391 [http-8080-5] ERROR org.hibernate.util.JDBCExceptionReporter - Duplicate entry '2009062323162784330' for key 'PRIMARY' 783391 [http-8080-5] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update[/color] 能有什么办法解决吗 [b]问题补充:[/b] sql 语句 为:insert 怎样做才变成update 问题补充: [DEBUG] 2009-06-26 13:26:28,640 [org.springframework.transaction.interceptor.AbstractFallbackTransactionAttributeSource.getTransactionAttribute(AbstractFallbackTransactionAttributeSource.java:107)] Adding transactional method [save] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT] Hibernate: insert into T_MODULE (DATECREATED, DATEMODIFED, DELETED, NAME, REMARK, OPTLOCK, HREF, HREFTARGET, LEAF, LEVEL, PARENTID, QTIP, TEXT, UIPROVIDER, DESCRIPTION, MODULENAME, URL, ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 114829 [http-8080-6] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000 114829 [http-8080-6] ERROR org.hibernate.util.JDBCExceptionReporter - Duplicate entry '2009062611061317130' for key 'PRIMARY' 114829 [http-8080-6] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
SSH框架Hibernate基于Spring自动生成的DAO怎样使用
applicantContext.xml ``` <?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx"> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="UserDAO" class="org.dao.UserDAO"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> </beans> ``` Hibernate.cfg.xml ``` <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/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/ </property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="myeclipse.connection.profile">mysql</property> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="cache.use_query_cache">true</property> <property name="cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property> <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property> <property name="current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property> <mapping resource="org/vo/User.hbm.xml" /> </session-factory> </hibernate-configuration> ``` UserDAO类 ``` public class UserDAO { private static final Logger log = LoggerFactory.getLogger(UserDAO.class); // property constants public static final String UNAME = "uname"; public static final String PASSWORD = "password"; private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } private Session getCurrentSession() { return sessionFactory.getCurrentSession(); } protected void initDao() { // do nothing } public void save(User transientInstance) { log.debug("saving User instance"); try { getCurrentSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(User persistentInstance) { log.debug("deleting User instance"); try { getCurrentSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public User findById(java.lang.Integer id) { log.debug("getting User instance with id: " + id); try { User instance = (User) getCurrentSession().get("org.vo.User", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List<?> findByExample(User instance) { log.debug("finding User instance by example"); try { List<?> results = getCurrentSession().createCriteria("org.vo.User") .add(Example.create(instance)).list(); 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 User instance with property: " + propertyName + ", value: " + value); try { String queryString = "from User as model where model." + propertyName + "= ?"; Query queryObject = getCurrentSession().createQuery(queryString); queryObject.setParameter(0, value); return queryObject.list(); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List<?> findByUname(Object uname) { return findByProperty(UNAME, uname); } public List<?> findByPassword(Object password) { return findByProperty(PASSWORD, password); } public List<?> findAll() { log.debug("finding all User instances"); try { String queryString = "from User"; Query queryObject = getCurrentSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public User merge(User detachedInstance) { log.debug("merging User instance"); try { User result = (User) getCurrentSession().merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(User instance) { log.debug("attaching dirty User instance"); try { getCurrentSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(User instance) { log.debug("attaching clean User instance"); try { getCurrentSession().buildLockRequest(LockOptions.NONE).lock( instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public static UserDAO getFromApplicationContext(ApplicationContext ctx) { return (UserDAO) ctx.getBean("UserDAO"); } } ``` HibernateSessionFactory类 ``` public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration(); private static ServiceRegistry serviceRegistry; static { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } } ``` 测试类 ``` package org.action; import org.dao.UserDAO; import org.vo.User; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub // Session session = HibernateSessionFactory.getSession(); // session.beginTransaction(); // 插入数据 // session.save(new User("大傻", "123")); // 通过id查询数据 // User user = (User) session.load(User.class, 1); // System.out.println(user.getPassword()); // 通过id查找并删除数据 // User user = (User) session.get(User.class, 8); // session.delete(user); // 通过id查找并修改数据 // User user = (User) session.load(User.class, 9); // user.setPassword("999999"); // session.saveOrUpdate(user); // UserDAO userDAO = new UserDAO(); User user = new User("Jone", "111111"); userDAO.save(user); // session.getTransaction().commit(); // session.close(); } } ``` * 错误提示 ``` SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Exception in thread "main" java.lang.NullPointerException at org.dao.UserDAO.getCurrentSession(UserDAO.java:41) at org.dao.UserDAO.save(UserDAO.java:51) at org.action.Test.main(Test.java:40) ``` 第一行指向 ``` UserDAO的private Session getCurrentSession() { return sessionFactory.getCurrentSession(); } ``` 第二行错误指向 ``` public void save(User transientInstance) { log.debug("saving User instance"); try { # getCurrentSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } ```
hibernate 问题
public class LoginService { private Login mb; private LoginImpl loginImpl; public LoginImpl getLoginImpl() { return loginImpl; } public void setLoginImpl(LoginImpl loginImpl) { this.loginImpl = loginImpl; } public Login getMb() { return mb; } public void setMb(Login mb) { this.mb = mb; } public String creat(){ mb.getPwd(); mb.getUsername(); System.out.println(mb.getPwd()+"++++++++++++++++++");//确实得到值了从前台 System.out.println(mb.getUsername()+"-------------------");//确实得到值了从前台 loginImpl.creatMember(mb);//这里是null 为什么?? return "success"; } public class LoginImpl { static Session session = null; public void creatMember(Object o){ try{ session = sessionFactory.opensession(); Transaction tx = session.beginTransaction(); session.save(o); tx.commit(); }catch(HibernateException ex){ ex.printStackTrace(); } } } 下面是sessionfactory的方法 package util; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class sessionFactory { private static SessionFactory sf =null; public static void Session(){ try{ sf = new Configuration().configure().buildSessionFactory(); }catch(HibernateException ex){ throw new RuntimeException("Exception is"+ex.getMessage()); } } public static Session opensession (){ Session s = sf.openSession(); return s; } public static void closeSession(Session s){ if(s!=null) s.close(); } } 请问各位高手们 我想传过去一个对象 mb 然后save(mb)入库,进入MyEclipse调试看见 为啥loginImpl.creatMember(mb)为null啊??还有就是请问 我这么用hibernate 对嘛?
hibernate3 的多对一的外键更新问题!
[code="ruby"] public class SysModel extends BaseEntity<SysModel> { @ManyToOne(cascade = { CascadeType.MERGE }) @JoinColumn(name = "PARENT_ID") private SysModel sysModel; ....... } [/code] 映射文件大概如此, 有一个自关联字段。 在操作的时候,遇到一个问题,当此字段为 null 的时候,我可以保存,但是不能更新,报错: Hibernate: update SYS_MODEL set DELETE_FLAG=?, MODEL_NAME=?, ORDER_ID=?, remark=?, PARENT_ID=?, url=?, version=? where id=? 2008-09-10 09:55:31,906 ERROR [org.hibernate.event.def.AbstractFlushingEventListener] - <Could not synchronize database state with session> org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.sctt.system.sys.model.bean.SysModel at org.hibernate.engine.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:219) at org.hibernate.type.EntityType.getIdentifier(EntityType.java:397) at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:78) 也就是说,PARENT_ID=? 为 NULL 。我基本知道错误原因。 但是,我的本条数据,确实 没有外键呀, sysModel = null; 如何才能更新 这样的数据呢?往高人回答。
今天在开发网站时候,遇到异常问题
这是我的代码: public class GroupDao implements IDao { [color=darkred]Session session = HibernateSessionFactory.getSession(); Transaction tran = session.beginTransaction();[/color] public void insert(Object obj) { Group group = (Group) obj; session.save(group); tran.commit(); HibernateSessionFactory.closeSession(); } public List queryAll() { String hql = "from Group"; Query query = session.createQuery(hql); List list = query.list(); HibernateSessionFactory.closeSession(); return list; } } jsp页面上报的错 exception javax.servlet.ServletException:[color=red]Session is closed![/color] org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:523) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:421) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194) org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) javax.servlet.http.HttpServlet.service(HttpServlet.java:763) javax.servlet.http.HttpServlet.service(HttpServlet.java:856) com.school.QuanXianFilter.FilterEncoding.doFilter(FilterEncoding.java:23) root cause org.hibernate.SessionException: [color=red]Session is closed![/color] org.hibernate.impl.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:49) org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:526) org.hibernate.impl.SessionImpl.save(SessionImpl.java:518) org.hibernate.impl.SessionImpl.save(SessionImpl.java:514) com.school.QuanXianIDaoImpl.GroupDao.insert(GroupDao.java:26) com.school.QuanXianAction.Action.addGroup(Action.java:36) 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:585) org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:274) org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:194) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194) org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432) javax.servlet.http.HttpServlet.service(HttpServlet.java:763) javax.servlet.http.HttpServlet.service(HttpServlet.java:856) com.school.QuanXianFilter.FilterEncoding.doFilter(FilterEncoding.java:23) 当我执行了插入以后,在返回页面,执行查询(queryAll())方法后,jsp页面却抛出了以上异常信息 研究了好长时间,可是没找出错误的原因。
在Spring集成Hibernate后,进行save操作报错
在进行save操作时抛出Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.异常 在网上找了许久,全是千篇一律。基本上都是说在web.xml的过滤器加FlushMode,但是我这个只有Spring+Hibernate,哪来的web.xml。也有说加事务处理的,但是我加了事务,测试了无数遍,还是不行,请大神们帮忙下,谢谢,下面是我的xml配置 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- Stock business object --> <bean id="stockBo" class="com.yiibai.stock.bo.impl.StockBoImpl" > <property name="stockDao" ref="stockDao" /> </bean> <bean id="stockDao" class="com.yiibai.stock.dao.impl.StockDaoImpl" > <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionManager" ref="transactionManager" /> <property name="transactionAttributes"> <props> <prop key="save">PROPAGATION_SUPPORTS</prop> </props> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="dataSource" ref="dataSource" /> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="productBoProxy" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="target" ref="stockDao" /> <property name="interceptorNames"> <list> <value>transactionInterceptor</value> </list> </property> </bean> </beans> 下面是具体错误信息 Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition. at org.springframework.orm.hibernate5.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1093) at org.springframework.orm.hibernate5.HibernateTemplate.lambda$update$13(HibernateTemplate.java:658) at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:383) at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:349) at org.springframework.orm.hibernate5.HibernateTemplate.update(HibernateTemplate.java:657) at org.springframework.orm.hibernate5.HibernateTemplate.update(HibernateTemplate.java:652) at com.yiibai.stock.dao.impl.StockDaoImpl.update(StockDaoImpl.java:17) at com.yiibai.stock.bo.impl.StockBoImpl.update(StockBoImpl.java:20) at com.yiibai.common.App.main(App.java:28)
hibernate 高手进
还是以前的一个题目,一直没有解决 classroom(班级)与student(学生)一对多双向关系 现在我ClassRoom room=(ClassRoom)session.get(ClassRoom.class,new Integer(1));返回一个持久化对象 接着我有定义了一个临时对象ClassRoom room1=new ClassRoom();现在我想让room.getSet()返回的集合放到room1对象中去; 网上高手说要对room.getSet()这个set克隆,可是最近我一直没有实验成功 public void testAA2(){ HibernateUtil.beginTransaction(); Session session=HibernateUtil.getCurrentSession(); ClassRoom room=(ClassRoom)session.get(ClassRoom.class,new Integer(1)); room.getSet().iterator(); ClassRoom room1=new ClassRoom(); Set<Student> set=new HashSet<Student>(); try { room1=(ClassRoom)room.colneObject(); //克隆room set=room1.getSet(); room1.setName("0003"); room1.setSet(set); session.save(room1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } session.getTransaction().commit(); session.close(); } 一直出错,Found shared references to a collection:set 估计还是没有克隆好,我的colneObject()方法是 public class ClassRoom implements java.io.Serializable,java.lang.Cloneable{ private Integer id; private String name; private Set<Student> set=new HashSet<Student>(); public Set<Student> getSet() { return set; } public void setSet(Set<Student> set) { this.set = set; } public ClassRoom() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Object colneObject() throws CloneNotSupportedException{ return super.clone(); } } 请高手帮我解决一下,谢谢 ;;;;;;;;;;;;;;;; 另外我认为还有一种方法可以实现,就是取得room对象,然后关掉session,然后保存,代码如下: public void testAA3(){ HibernateUtil.beginTransaction(); Session session=HibernateUtil.getCurrentSession(); ClassRoom room=(ClassRoom)session.get(ClassRoom.class,new Integer(1)); room.getSet().iterator(); session.close(); Session session2=HibernateUtil.getCurrentSession();//这样写报错如下: //org.hibernate.SessionException: Session is closed!... ..... //Session session2=HibernateUtil.getCurrentSession();////如果这样写报错如下 //org.hibernate.HibernateException: No CurrentSessionContext configured! .... ClassRoom room1=new ClassRoom(); Set<Student> set2=new HashSet<Student>(); room1.setName("0003"); room1.setSet(room.getSet()); session2.save(room1); session2.getTransaction().commit(); session2.close(); } 可是这样写还是一直报错,还是一直没有保存成功!!! 哪位好心人指点一下以上两个问题怎么解决呀
应用中程序通过getBean方式 得到spring中 hibernate sessionFactory问题
应用中程序通过getBean方式 得到spring中 hibernate sessionFactory问题: 程序使用正常方式是正常的 然后报错的地方为session.save(Object) 模式已经在配置文件中设定, 且程序中hibernate sql语句正常。 但报错莫名出 现ADMINISTRATOR.I_FITDETAIL,始终找不到原因,请告知。 Hibernate: insert into ADMIN.fitdetail (fit_detail_flag, fit_detail_no, matereil_fit_id, materiel_count, materiel_key, materiel_name, materiel_no, materiel_price, materiel_unit, m_unit_id, total_price, fit_detail_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 2010-05-20 17:43:01 WARN JDBCExceptionReporter:100 - SQL Error: -723, SQLState: 09000 2010-05-20 17:43:01 ERROR JDBCExceptionReporter:101 - DB2 SQL error: SQLCODE: -723, SQLSTATE: 09000, SQLERRMC: ADMINISTRATOR.I_FITDETAIL;-407;23502;TBSPACEID=2, TABLEID=535, COLNO=1 2010-05-20 17:43:01 ERROR AbstractFlushingEventListener:324 - Could not synchronize database state with session org.hibernate.exception.GenericJDBCException: could not insert: [com.iss.delver.entity.FitDetail] at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:126) at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:114) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2285) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2678) at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137) at com.ibm.crl.dis.dao.impl.DISHibernateDAOImpl.createBO(DISHibernateDAOImpl.java:57) at com.ibm.crl.dis.service.DISBaseCRUDService.createBO(DISBaseCRUDService.java:32) at com.ibm.crl.dis.util.DISFeedXMLUtil.invokeCRUDBOByDISService(DISFeedXMLUtil.java:625) at com.ibm.crl.dis.util.DISFeedXMLUtil.crudBOTypeByDISService(DISFeedXMLUtil.java:585) at com.ibm.crl.dis.util.DISFeedXMLUtil.parseReceivedFeedAndBuildReturnFeedForByBO(DISFeedXMLUtil.java:340) at com.ibm.crl.dis.servlet.ReceiveDataFromDISServlet.parseReceivedFeedAndSendFeed(ReceiveDataFromDISServlet.java:68) at com.ibm.crl.dis.servlet.ReceiveDataFromDISServlet.doPost(ReceiveDataFromDISServlet.java:53) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.iss.delver.common.util.ResponseFilter.doFilter(ResponseFilter.java:34) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.iss.delver.common.util.CashFilter.doFilter(CashFilter.java:40) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:96) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Thread.java:619) Caused by: com.ibm.db2.jcc.c.SqlException: DB2 SQL error: SQLCODE: -723, SQLSTATE: 09000, SQLERRMC: ADMINISTRATOR.I_FITDETAIL;-407;23502;TBSPACEID=2, TABLEID=535, COLNO=1 at com.ibm.db2.jcc.c.fg.d(fg.java:1340)
关于hibernate的getSession()的问题
我想写一个hibernate的基础类,部分代码如下: [code="java"] package cn.sanxing.model.util; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; /** * 通用的DAO实现方法,提供了持久化操作的基础方法 * */ public class HibernateDAO { public void saveObject(Object obj) { getSession().save(obj); } } [/code] 其中getSession().save(obj);这行一直提示“The Method getSession() is undefined for the type HibernateDAO” 我不是很清楚,请大家帮我看看是什么原因造成的,怎么解决?
Hibernate4 No Session found for current thread异常
标题:Hibernate4 No Session found for current thread与createQuery is not valid without active transaction异常 描述: 在项目程序运行时遇到了Hibernate4 No Session found for current thread异常, ![图片说明](https://img-ask.csdn.net/upload/201610/07/1475829970_705784.png) 百度了一下 在hibernate的配置文件中加入了<property name="current_session_context_class">thread</property> 配置并且处理业务逻辑的类上也加入了注解如下 package com.xiaonei.baseService; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Transactional; @Transactional public class BaseServiceImpl implements BaseService { @Resource private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * @author sunlong * @param hql:传入的hql,可以带参数? * @param args: 问号对应的参数数组 */ @Override public List<?> getResult(String hql, Object[] args) { Session session = sessionFactory.getCurrentSession(); System.out.println("执行到创建Session"); Query query = session.createQuery(hql); System.out.println("执行到Query"); if(args!= null && args.length > 0){ for(int i = 0;i<args.length;i++){ query.setParameter(i, args[i]); } } return query.list(); } 但是当我再次运行程序时,出现了createQuery is not valid without active transaction异常 ![图片说明](https://img-ask.csdn.net/upload/201610/07/1475830288_371841.png) 然后我就接着百度,解决方法是把hibernate配置文件中的<property name="current_session_context_class">thread</property> 配置删除或者把值thread改成org.springframework.orm.hibernate3.SpringSessionContext 再次运行却又出现了org.springframework.orm.hibernate3.SpringSessionContext异常整了好久都没搞明白,这是为什么呀? Spring 的配置文件 1.applicationContext.xml <!-- 导入资源文件 --> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置 C3P0 数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!-- 配置 SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <property name="mappingLocations" value="classpath:com/xiaonei/domain/*.hbm.xml"></property> </bean> <!-- 配置 Spring 的声明式事务 --> <!-- 1. 配置 hibernate 的事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 2. 配置事务属性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="lastNameIsValid" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 3. 配置事务切入点, 再把事务属性和事务切入点关联起来 --> <aop:config> <aop:pointcut expression="execution(* com.xiaonei.service.*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config> <!-- 自动装配具有注解的属性 --> <context:component-scan base-package="com.xiaonei.service"></context:component-scan> </beans> 2.applicationContextbeans.xml <import resource="applicationContext.xml"/> <bean id="countryService" class="com.xiaonei.service.serviceImpl.CountryServiceImpl"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="provinceService" class="com.xiaonei.service.serviceImpl.ProvinceServiceImpl"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="universityService" class="com.xiaonei.service.serviceImpl.UniversityServiceImpl"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="registerAction" class="com.xiaonei.action.RegisterAction"> <property name="countryService" ref="countryService"></property> <property name="provinceService" ref="provinceService"></property> <property name="universityService" ref="universityService"></property> </bean> baseServiceImpl.java package com.xiaonei.service.baseService; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public abstract class BaseServiceImpl implements BaseService { @Resource private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } /** * @author sunlong * @param hql:传入的hql,可以带参数? * @param args: 问号对应的参数数组 */ @Transactional public List<?> getResult(String hql, Object[] args) { System.out.println("执行了getResult方法"); Query query = sessionFactory.getCurrentSession().createQuery(hql); System.out.println("执行到createQuery方法"); if(args!= null && args.length > 0){ for(int i = 0;i<args.length;i++){ query.setParameter(i, args[i]); } } return query.list(); } @Override public void save(Object obj) { // TODO Auto-generated method stub } @Override public void delete(Object obj) { // TODO Auto-generated method stub } @Override public void update(Object obj) { // TODO Auto-generated method stub } @Override public Object findById(Class<?> calzz, Integer id) { // TODO Auto-generated method stub return null; } }
Hibrernate中的Dao
个位大虾 看看小弟写的 使用Hibernate有没有什么问题 或是需要规范的 谢谢。 先声明个Session private static Session session; 这个是获得数据库中某个表的所有数据 public List getByAll(String hql){ try{ session = HibernateSessionFactory.getSession(); Query query = session.createQuery(hql); List list = query.list(); return list; }catch(Exception e){ e.printStackTrace(); } return null; } 这个是获得数据库中单个列的数据 public Object getById(Object o,int id) { session = HibernateSessionFactory.getSession(); Object obj; try{ obj = session.get(o.getClass(),new Integer(id)); }catch(Exception e){ obj = new Object(); e.printStackTrace(); }finally{ } return obj; } 这个是存入数据库中的方法 public void saveExecuteQuery(Object o) { session = HibernateSessionFactory.getSession(); Transaction tx = session.beginTransaction(); try{ session.save(o); tx.commit(); }catch(Exception e){ tx.rollback(); e.printStackTrace(); }finally{ } } 这个是修改数据库中某个列的值 public void updateExcuteUpdate(String hql) { session = HibernateSessionFactory.getSession(); Transaction tx = session.beginTransaction(); try{ Query query = session.createQuery(hql); query.executeUpdate(); tx.commit(); }catch(Exception e){ tx.rollback(); e.printStackTrace(); }finally{ } } 删除某条数据 public void deleteExcuteUpdate(String hql) { session = HibernateSessionFactory.getSession(); Query query = session.createQuery(hql); Transaction tx = session.beginTransaction(); try{ query.executeUpdate(); tx.commit(); }catch(Exception e){ e.printStackTrace(); tx.rollback(); }finally{ } } 手动关闭Session public void closeSession(){ session.close(); } [b]问题补充:[/b] 哦,我已经跑起来了。我给了10分吖 还逮也给说说如何改进。 [b]问题补充:[/b] 我对于静态的理解不是很透彻 在这里我写的private static Session session; 开始的时候写的是 private Session session。 但想想了 怕出错 就用static。能不能给我详解一下 为什么不用static 我想的就是用个单列 最好是一个用户一个session 不必每次都实例化一个session 最好能给举例说明一下好处。 [b]问题补充:[/b] 呵呵,我昨天买了本设计模式方面的书,正在努力的研究中... ... [b]问题补充:[/b] 再弱弱的问一句 session这个时候应该用什么关闭 是session.colse还是HibernateSessionFactory.closeSession() 我准备在所有的方法的 try{ .. .. 代码中 .. .. }catch(Exception e){ HibernateSessionFactory.closeSession() e.printStackTrace(); } 有没有问题 还是这两种关闭的不同
外键保存,session报错!
[b]异常信息: org.springframework.orm.hibernate3.HibernateSystemException: a different object with the same identifier value was already associated with the session: [com.office.vo.UserInfo#1]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.office.vo.UserInfo#1] Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.office.vo.UserInfo#1] at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:587) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:284) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:223) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:89) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70) at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507) at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499) at org.hibernate.engine.CascadingAction$1.cascade(CascadingAction.java:218) at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:268) at org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:216) at org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:169) at org.hibernate.engine.Cascade.cascade(Cascade.java:130) at org.hibernate.event.def.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:131) at org.hibernate.event.def.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:122) at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:65) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) at org.springframework.orm.hibernate3.SpringSessionSynchronization.beforeCommit(SpringSessionSynchronization.java:126) at org.springframework.transaction.support.TransactionSynchronizationUtils.triggerBeforeCommit(TransactionSynchronizationUtils.java:48) at org.springframework.transaction.support.AbstractPlatformTransactionManager.triggerBeforeCommit(AbstractPlatformTransactionManager.java:824) at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:634) at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:621) at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:311) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:117) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:206) at $Proxy2.addDepart(Unknown Source) at com.office.struts.DepartAction.addDepart(DepartAction.java:157) action类: public String addDepart(){ HttpServletRequest req=ServletActionContext.getRequest(); departInfo=new DepartInfo(); departInfo.setDepartName(this.getDepartName()); departInfo.setConnectMobileTelNo(this.getCell()); departInfo.setConnectNo(this.getTel()); departInfo.setUserinfo(userService.getUserByUserName(this.getPrincipalUserName())); departInfo.setBranchinfo((BranchInfo)branchService.getBranch(this.getBranchId()).get(0)); try { departService.addDepart(departInfo); req.setAttribute("UserMsg", 7); return "UserMsg"; } catch (Exception e) { e.printStackTrace(); req.setAttribute("UserMsg", 8); return "UserMsg"; } } dao类: public boolean addDepart(DepartInfo depart) { // TODO Auto-generated method stub try { this.getHibernateTemplate().saveOrUpdate(depart); this.getHibernateTemplate().refresh(depart); return true; } catch (DataAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } Hibernate 配置 userinfo表 <hibernate-mapping> <class name="com.office.vo.UserInfo" table="userinfo" catalog="cardsale"> <id name="id" type="java.lang.Integer"> <column name="ID" /> <generator class="increment" /> </id> <many-to-one name="departinfo" class="com.office.vo.DepartInfo" fetch="select" lazy="false" cascade="save-update"> <column name="DepartId" /> </many-to-one> <many-to-one name="userstate" class="com.office.vo.UserState" fetch="select" lazy="false"> <column name="UserState" /> </many-to-one> <many-to-one name="roleinfo" class="com.office.vo.RoleInfo" fetch="select" lazy="false"> <column name="RoleId" /> </many-to-one> <property name="userId" type="java.lang.String"> <column name="UserId" length="50" /> </property> <property name="userName" type="java.lang.String"> <column name="UserName" length="50" /> </property> <property name="pwd" type="java.lang.String"> <column name="PWd" length="50" /> </property> <property name="gender" type="java.lang.Integer"> <column name="Gender" /> </property> <set name="departinfos" inverse="false" cascade="save-update"> <key> <column name="PrincipalUser" not-null="false" /> </key> <one-to-many class="com.office.vo.DepartInfo" /> </set> </class> </hibernate-mapping> departinfo表 <hibernate-mapping> <class name="com.office.vo.DepartInfo" table="departinfo" catalog="cardsale"> <id name="departId" type="java.lang.Integer"> <column name="DepartId" /> <generator class="increment" /> </id> <many-to-one name="branchinfo" class="com.office.vo.BranchInfo" fetch="select" cascade="save-update" lazy="false"> <column name="BranchId" not-null="true" /> </many-to-one> <many-to-one name="userinfo" class="com.office.vo.UserInfo" fetch="select" cascade="save-update" lazy="false"> <column name="PrincipalUser" not-null="false" /> </many-to-one> <property name="departName" type="java.lang.String"> <column name="DepartName" length="50" not-null="false" /> </property> <property name="connectNo" type="java.lang.Long"> <column name="ConnectNo" not-null="true" /> </property> <property name="connectMobileTelNo" type="java.lang.Long"> <column name="ConnectMobileTelNo" not-null="true" /> </property> <property name="faxes" type="java.lang.Long"> <column name="Faxes" not-null="true" /> </property> <set name="userinfos" inverse="true" lazy="false" cascade="all"> <key> <column name="departId" not-null="false" ></column> </key> <one-to-many class="com.office.vo.UserInfo" /> </set> </class> </hibernate-mapping> branchinfo表 <hibernate-mapping> <class name="com.office.vo.BranchInfo" table="branchinfo" catalog="cardsale"> <id name="branchId" type="java.lang.Integer"> <column name="BranchId" /> <generator class="increment" /> </id> <property name="branchName" type="java.lang.String"> <column name="BranchName" length="50" not-null="true" /> </property> <property name="branchShortName" type="java.lang.String"> <column name="BranchShortName" length="50" not-null="true" /> </property> <set name="departinfos" inverse="true" lazy="false" cascade="all"> <key> <column name="BranchId" not-null="false" /> </key> <one-to-many class="com.office.vo.DepartInfo" /> </set> </class> </hibernate-mapping>[/b]
NHibernate 保存实体类时无法转换类型
求NHibernate会的请教! 实体类:Userinfo 和 Userinfo.hbm.xml是用codesmith生成的。userinfo属性如下: protected Guid _id; protected string _userName; protected string _password; protected string _email; protected int _state = 0 ; protected string _passwordQuestion; protected string _passwordAnswer; protected string _nick; protected string _realName; protected string _images; protected string _backgroundImage; protected bool _sex; protected string _mobilePhone; protected string _address; protected DateTime _birthday; protected string _loastLoginIP; protected DateTime _regTime; protected int _isDel; protected DateTime _beginTime = DateTime.Now ; protected DateTime _updateTime; protected UserRole _userRole; protected IList _newsCommentsReplies; protected IList _publishNewses; protected IList _newsCommentses; protected IList _userFavorClasses; 我写个userdao 保存实体类 userinfo,代码如下: ICriteria criteria = _session.CreateCriteria(typeof(UserRole)); userInfo.UserRole = (UserRole)criteria.List<UserRole>()[0]; _session.Save(userInfo); _session.Flush(); Save的时候抛出异常: 无法将类型为“System.Collections.ArrayList”的对象强制转换为类型“Syste m.Collections.Generic.IEnumerable`1[System.Object]” 估计是上面实体类的属性与保存时映射的类型不搭配。但都是工具生成的,不知道要怎么改。求解!!
hibernate 手动控制事务回滚失败
spring配置: <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://192.168.0.124:3306/art8k?useUnicode=true&amp;characterEncoding=utf-8" /> <property name="user" value="root" /> <property name="password" value="123456" /> <property name="initialPoolSize"><value>5</value></property> <property name="minPoolSize"><value>20</value></property> <property name="maxPoolSize"><value>100</value></property> <property name="acquireIncrement"><value>5</value></property> <property name="maxIdleTime"><value>100</value></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.show_sql=true hibernate.format_sql=false </value> </property> <property name="packagesToScan" value="com.art8k.platform.*.*.bean"/> </bean> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="list*" read-only="true"/> <tx:method name="*" rollback-for="Exception"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="operation" expression="execution(* com.art8k.platform..service.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="operation" /> </aop:config> <bean id="dao" class="com.art8k.platform.dao.IDaoManager"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="baseService" abstract="true" class="com.art8k.platform.service.BaseService"> <property name="dao"> <ref bean="dao"/> </property> </bean> BaseService.java public BaseService() { if (SpringUtil.getWebApplicationContext()!=null && SpringUtil.getWebApplicationContext().getBean("dao") != null) { this.dao = (IDaoManager) SpringUtil.getWebApplicationContext().getBean("dao"); } } /** * 数据库操作 dao */ @SuppressWarnings("unchecked") @Resource protected IDaoManager dao; @SuppressWarnings("unchecked") public void setDao(IDaoManager dao) { this.dao = dao; } @SuppressWarnings("unchecked") public IDaoManager getDao() { return dao; } IDaoManager.java public class IDaoManager<T, P, PK extends Serializable> extends HibernateDaoSupport implements GeneraDAO<T, P, PK> { /** * <p> * 持久化业务逻辑数据对象 ,无返回值 * </p> */ public void saveIObject(final T object) { getHibernateTemplate().save(object); } /** * <p> * 持久化业务逻辑数据对象,新增或者更新 ,无返回值 * </p> * * @param object * T 业务逻辑数据对象 */ public void saveOrUpdateIObject(final T object) { getHibernateTemplate().saveOrUpdate(object); } 我自己的service集成BaseService,我在service里的一个方法内插入两条数据,如果出现异常,把本次对数据库的所有操作回滚,现在问题是回滚失败,代码如下: public int saveProduct(HmProduct hmProduct) { int result = ConstanData.SUCCESSCODE; Session sessions = null; sessions = this.getDao().getHibernateTemplate().getSessionFactory().openSession(); sessions.beginTransaction(); try { sessions.save(hmProduct); HmProductLog hmProductLog = new HmProductLog(); hmProductLog.setProductId(hmProduct.getId()); hmProductLog.setPrice(hmProduct.getPrice()); hmProductLog.setCreateTime(new Date()); sessions.save(hmProductLog); } catch (Exception e) { // TODO Auto-generated catch block sessions.getTransaction().rollback(); result = ConstanData.FAILURECODE; e.printStackTrace(); }finally{ sessions.close(); } return result; }
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
前端 | 2. 正则
转载请注明以下: 本文转自清自以敬的博客:https://blog.csdn.net/qq_45791147 文章目录1.转义2.正则表达式初步2.1.匹配字符2.1.1.组成元素2.1.2.基础正则的设计 1.转义 转义的作用: 当某个字符在表达式中具有特殊含义,例如字符串引号中出现了引号,为了可以使用这些字符本身,而不是使用其在表达式中的特殊含义,则需要通过转义符“\”来构建该字符转义...
有哪些让程序员受益终生的建议
从业五年多,辗转两个大厂,出过书,创过业,从技术小白成长为基层管理,联合几个业内大牛回答下这个问题,希望能帮到大家,记得帮我点赞哦。 敲黑板!!!读了这篇文章,你将知道如何才能进大厂,如何实现财务自由,如何在工作中游刃有余,这篇文章很长,但绝对是精品,记得帮我点赞哦!!!! 一腔肺腑之言,能看进去多少,就看你自己了!!! 目录: 在校生篇: 为什么要尽量进大厂? 如何选择语言及方...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小型人工智障。 知识可以运用在不同地方,不一定非是天气预报。
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
Docker 从入门到掉坑
Docker 介绍 简单的对docker进行介绍,可以把它理解为一个应用程序执行的容器。但是docker本身和虚拟机还是有较为明显的出入的。我大致归纳了一下,可以总结为以下几点: docker自身也有着很多的优点,关于它的优点,可以总结为以下几项: 安装docker 从 2017 年 3 月开始 docker 在原来的基础上分为两个分支版本: Docker CE 和 Doc...
为啥国人偏爱Mybatis,而老外喜欢Hibernate/JPA呢?
关于SQL和ORM的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行了一番讨论,感触还是有一些,于是就有了今天这篇文。 声明:本文不会下关于Mybatis和JPA两个持久层框架哪个更好这样的结论。只是摆事实,讲道理,所以,请各位看官勿喷。 一、事件起因 关于Mybatis和JPA孰优孰劣的问题,争论已经很多年了。一直也没有结论,毕竟每个人的喜好和习惯是大不相同的。我也看...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
Python 编程开发 实用经验和技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法和技巧,包括小数保留指定位小数、判断变量的数据类型、类方法@classmethod、制表符中文对齐、遍历字典、datetime.timedelta的使用等,会持续更新......
YouTube排名第一的励志英文演讲《Dream(梦想)》
Idon’t know what that dream is that you have, I don't care how disappointing it might have been as you've been working toward that dream,but that dream that you’re holding in your mind, that it’s po...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员...
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC...
相关热词 c# 引用mysql c#动态加载非托管dll c# 两个表数据同步 c# 返回浮点json c# imap 链接状态 c# 漂亮字 c# 上取整 除法 c#substring c#中延时关闭 c#线段拖拉
立即提问