1

我创建了一个 spring-hibernate 项目,但是当我尝试运行我的应用程序时出现以下错误。

我在这里提供相关的课程。

资源/spring-config.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="configLocation" value="hibernate.cfg.xml"/>
    </bean>

    <context:annotation-config />
    <context:component-scan base-package="foo.bar, com.mkyong.stock"/>

</beans>

资源/hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.url">jdbc:mysql://localhost:3306/mkyong</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.username">root</property>
        <property name="connection.password">skia0987</property>

        <!-- DB schema will be updated if needed -->
        <property name="hbm2ddl.auto">create</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <mapping class="com.mkyong.stock.model.StockEntity"/>
        <mapping resource="mapping.xml"/>
    </session-factory>
</hibernate-configuration>

foo.bar/HelloApp.java :

package foo.bar;

import com.mkyong.stock.bo.StockBo;
import com.mkyong.stock.model.StockEntity;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

        StockBo stockBo = (StockBo)context.getBean("stockBo");

        //insert
        StockEntity stock = new StockEntity();
        stock.setStockCode("7668");
        stock.setStockName("HAIO");
        stockBo.save(stock);

        //select
        StockEntity stock2 = stockBo.findByStockCode("7668");
        System.out.println(stock2);

        //update
        //stock2.setStockName("HAIO-1");
        //stockBo.update(stock2);

        //delete
        //stockBo.delete(stock2);

        System.out.println("Done");
    }
}

com.mkyong.stock.bo/StockBoImpl.java:

package com.mkyong.stock.bo;

import com.mkyong.stock.dao.StockDao;
import com.mkyong.stock.model.StockEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("stockBo")
public class StockBoImpl implements StockBo{

    @Autowired
    StockDao stockDao;

    public void setStockDao(StockDao stockDao)
    {
        this.stockDao = stockDao;
    }

    @Override
    public void save(StockEntity stock) {
        stockDao.save(stock);
    }

    @Override
    public void update(StockEntity stock) {
        stockDao.save(stock);
    }

    @Override
    public void delete(StockEntity stock) {
        stockDao.delete(stock);
    }

    @Override
    public StockEntity findByStockCode(String stockCode) {
        return stockDao.findByStockCode(stockCode);
    }
}

com.mkyong.stock.dao/StockDaoImpl.java:

package com.mkyong.stock.dao;

import com.mkyong.stock.model.StockEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("stockDao")
public class StockDaoImpl implements StockDao{

    private SessionFactory sessionFactory;

    @Autowired
    public StockDaoImpl(SessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
    }

    private Session currentSession()
    {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void save(StockEntity stock) {
        currentSession().save(stock);
    }

    @Override
    public void update(StockEntity stock) {
        currentSession().update(stock);
    }

    @Override
    public void delete(StockEntity stock) {
        currentSession().delete(stock);
    }

    @Override
    public StockEntity findByStockCode(String stockCode) {
        return (StockEntity)currentSession().get(StockEntity.class, stockCode);
    }
}

com.mkyong.stock.model/StockEntity.java :

package com.mkyong.stock.model;

import javax.persistence.*;

import java.io.Serializable;

import static javax.persistence.GenerationType.IDENTITY;


@javax.persistence.Table(name = "stock", schema = "", catalog = "mkyong",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "STOCK_NAME"),
                @UniqueConstraint(columnNames = "STOCK_CODE")
        }
)
@Entity
public class StockEntity implements Serializable{
    private int stockId;
    private String stockCode;
    private String stockName;

    //---constructors
    public StockEntity() {
    }

    public StockEntity(String stockCode, String stockName) {
        this.stockCode = stockCode;
        this.stockName = stockName;
    }

    //---getters and setters
    @javax.persistence.Column(name = "STOCK_ID", unique = true, nullable = false, insertable = true, updatable = true, length = 10, precision = 0)
    @Id
    @GeneratedValue(strategy = IDENTITY)
    public int getStockId() {
        return stockId;
    }

    public void setStockId(int stockId) {
        this.stockId = stockId;
    }



    @javax.persistence.Column(name = "STOCK_CODE", unique = true, nullable = false, insertable = true, updatable = true, length = 10, precision = 0)
    @Basic
    public String getStockCode() {
        return stockCode;
    }

    public void setStockCode(String stockCode) {
        this.stockCode = stockCode;
    }



    @javax.persistence.Column(name = "STOCK_NAME", unique = true, nullable = false, insertable = true, updatable = true, length = 20, precision = 0)
    @Basic
    public String getStockName() {
        return stockName;
    }

    public void setStockName(String stockName) {
        this.stockName = stockName;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        StockEntity that = (StockEntity) o;

        if (stockId != that.stockId) return false;
        if (stockCode != null ? !stockCode.equals(that.stockCode) : that.stockCode != null) return false;
        if (stockName != null ? !stockName.equals(that.stockName) : that.stockName != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = stockId;
        result = 31 * result + (stockCode != null ? stockCode.hashCode() : 0);
        result = 31 * result + (stockName != null ? stockName.hashCode() : 0);
        return result;
    }

    @Override
    public String toString()
    {
        return "Stock [stockCode=" + stockCode + ", stockId=" + stockId + ", stockName=" + stockName + "]";
    }
}

关于如何解决该错误的任何想法?谢谢你。

更新:这是堆栈跟踪

Exception in thread "main" org.hibernate.HibernateException: No Session found for current thread
    at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1039)
    at com.mkyong.stock.dao.StockDaoImpl.currentSession(StockDaoImpl.java:29)
    at com.mkyong.stock.dao.StockDaoImpl.save(StockDaoImpl.java:34)
    at com.mkyong.stock.bo.StockBoImpl.save(StockBoImpl.java:28)
    at foo.bar.HelloApp.main(HelloApp.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
4

2 回答 2

0

hibernate.cfg.xml在Hibernate 4的文件中添加以下属性。

<property name="hibernate.current_session_context_class">thread</property>

或者

<property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>

对于其他版本。

这一行告诉 Hibernate aSession将绑定到线程上下文,这样当您第一次调用getCurrentSession()时,将创建一个会话并将其附加到正在运行的线程。同一线程中的任何未来调用都将返回相同的Session对象。

于 2013-04-23T17:31:09.263 回答
0

使用 Java-configs,我需要的解决方案是替换

<tx:annotation-driven/>

@EnableTransactionManagement
于 2013-12-16T14:15:09.473 回答