使用Hibernate将数据插入表中

时间:2016-08-04 13:59:36

标签: java hibernate

我是Hibernate的新手。我想将数据插入到这个hibernate实体中:

@Entity
public class Invitation implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "invited_on")
    @Temporal(TemporalType.TIMESTAMP)
    private Date invitedOn;

    @Column(name = "invited_email")
    private String invitedEmail;

    @Column(name = "invitation_msg")
    private String invitationMessage;

    private Boolean status; //true:accepted || false:pending

    @ManyToOne
    @JoinColumn(name = "sent_by")
    private Person inviter;

// getters and setters
}

我测试了这个代码

public void insert()
{
    Query query = session.createQuery("insert into Invitation(invited_on, invited_email, invitation_msg, sent_by)");
    int result = query.executeUpdate();
}

插入数据的正确方法是什么?我应该如何创建会话对象?

2 个答案:

答案 0 :(得分:1)

你有Hibernate和它的工具使用它们

免责声明:

  • 示例来自HERE
  • 动态编写的代码!!
  • 我没有使用status属性,因为没有映射!
// don't need if you already got a session
Session session = HibernateUtil.getSessionFactory().openSession();

// start transaction
session.beginTransaction();

// create invitation Object
Invitation inv = new Invitation();
inv.setId(1L);
inv.setInvitedOn(new java.util.Date());
inv.setInvitedEmail("yo@yo.com");
inv.setInvitationMessage("come on!!!");
inv.setInviter(new Person("inviter"));  // hey! this is not valid for sure! :)

// Save the invitation to database
session.save(inv);

// Commit the transaction
session.getTransaction().commit();

答案 1 :(得分:1)

在主类中使用它,它可以将数据插入到表中:

用户user = new Users();

    user.setUid(1);
    user.setUfname("firstname");
    user.setUlname("Lastname");

    Configuration config = new Configuration().configure().addAnnotatedClass(Users.class);
    ServiceRegistry reg = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
    SessionFactory sf = config.buildSessionFactory(reg);
    Session session = sf.openSession();

    Transaction tx = session.beginTransaction();
    session.save(user);

    tx.commit();