Java 如何使用spring + hibernate将数据插入到数据库中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26035114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:44:55  来源:igfitidea点击:

How to insert data into the database using spring + hibernate?

javamysqlspringhibernate

提问by user3189357

see i m havving user.java for the user info.

有关用户信息,请参阅 im havving user.java。

@Entity(name = "user")
@Table(name = "user")
public class User {

    @Id
    @Column(name = "id")
    private String id;  
    @Column(name = "password")
    private String password;
//getter and setter for this..
}

this is my userdao

这是我的用户道

public class UserDao {
    public interface UserDAO {
        public String insert(User user);

    }
}

and this is the impl class for inserting into database see this was my code.please check it and tell me what i m doing wrong

这是用于插入数据库的 impl 类,请查看这是我的代码。请检查它并告诉我我做错了什么

@Repository
@Transactional
public class UserImpl implements UserDAO {

    private DataSource dataSource;

    @Autowired
    SessionFactory sessionFactory;
    @Resource(name = "sessionFactory")
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public String insert(User use) {

        Session session = this.sessionFactory.openSession();
        try{

            Session sess = this.sessionFactory.getCurrentSession();              
            session.save(reg);


                        return (String)user.getUserName(); 
                        }catch(Exception e){
                            System.out.println("in catch"+e.getMessage());
                            e.printStackTrace();

    }

    }
}




} 

and in my controller after successful registration i m inserting data to the database by this

并在成功注册后在我的控制器中通过此将数据插入数据库

 userDao.insert(user);

but i m not getting output means not any data is inserting into the database.why this..? this is my mvc configuration

但我没有得到输出意味着没有任何数据插入到数据库中。为什么会这样..?这是我的 mvc 配置

<context:component-scan base-package="com.user.xyz" />
    <mvc:annotation-driven />
    <mvc:resources mapping="/resources/**" location="/resources/images/, /resources/css/" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />

    </bean>

回答by Phong Nguyen

Remember this: You don't have any exist session, but you use getCurrentSession(). To use this method, you must have a session already. try this:

请记住这一点:您没有任何现有会话,但您使用getCurrentSession(). 要使用此方法,您必须已经有一个会话。尝试这个:

Session session = this.sessionFactory.openSession();

Now you had a session for your transaction.

现在您有一个交易会话。

You should declare sessionFactory in an xml file (hibernate.xml or spring.xml), then use @Autowire to get it and open new session.

您应该在 xml 文件(hibernate.xml 或 spring.xml)中声明 sessionFactory,然后使用 @Autowire 获取它并打开新会话。

回答by przemek hertel

You have 2 choices:

您有 2 个选择:

A. force hibernate to flush any changes you have made in session:

A. 强制休眠刷新您在会话中所做的任何更改:

session.save(user);
session.flush();

B. make whole method run in transaction - this is much better of course. When transaction is commited - hibernate will flush any changes to database just if you would do manually.

B. 让整个方法在事务中运行——这当然要好得多。提交事务时 - 休眠将刷新对数据库的任何更改,就像您手动执行一样。

for example:

例如:

Transaction tx = null;

try {

  session.beginTransaction();

  session.save(user);
  ....

  tx.commit();

} catch (RuntimeException e) {
  tx.rollback();
  throw e;
}

回答by Mathias G.

If you have multiple DAO calls in a single request, then session.getCurrentSession() is useful, but I guess that is not your case. If there is only a single DAO call per request then session.openSession() is the right way.

如果您在单个请求中有多个 DAO 调用,那么 session.getCurrentSession() 很有用,但我想这不是您的情况。如果每个请求只有一个 DAO 调用,那么 session.openSession() 是正确的方法。

Take care that when using session.openSession(), you also have to close your session afterwards.

请注意,在使用 session.openSession() 时,您还必须在之后关闭会话。

The best thing to do is open a session for each incoming request (using a filter is the easiest way to do this) and then calling sessionFactory.getCurrentSession() in all your DAOs to get the current session. I guess your problem is you didn't specify the filter. That way all your DAOs will be easily reusable and you don't need to close your session afterwards.

最好的做法是为每个传入请求打开一个会话(使用过滤器是最简单的方法),然后在所有 DAO 中调用 sessionFactory.getCurrentSession() 以获取当前会话。我猜你的问题是你没有指定过滤器。这样,您的所有 DAO 都可以轻松重用,之后您无需关闭会话。

You can found more information in the docs: Hibernate documentation

您可以在文档中找到更多信息: Hibernate 文档

回答by Sai prateek

I have also faced the same issue, and got the solution. For now check below points-

我也遇到了同样的问题,并得到了解决方案。现在检查以下几点-

  1. Check for appropriate jar files you are using
  2. Check for manifest.mf in META-INF folder for application info.
  3. Check your hibernate configuration in configuration file for hibernate template configuration.
  4. At last if everything is OK then use session.flush()before insert.

    Session session = sessionFactory.openSession();
     Transaction tx = session.beginTransaction();
        {
           {
                //... your logic
                //flush a batch of inserts and release memory:
                session.flush();
                session.clear();
            }
        }

    tx.commit(); session.close()
  1. 检查您正在使用的适当 jar 文件
  2. 检查 META-INF 文件夹中的 manifest.mf 以获取应用程序信息。
  3. 检查配置文件中的休眠配置以获取休眠模板配置。
  4. 最后,如果一切正常,则session.flush()在插入之前使用。

    Session session = sessionFactory.openSession();
     Transaction tx = session.beginTransaction();
        {
           {
                //... your logic
                //flush a batch of inserts and release memory:
                session.flush();
                session.clear();
            }
        }

    tx.commit(); session.close()