Java 使用 Hibernate 将数据插入表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38769494/
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
Insert data into table using Hibernate
提问by Peter Penzov
I'm new to Hibernate. I want to insert data into this hibernate entity:
我是 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
}
I tested this code:
我测试了这段代码:
public void insert()
{
Query query = session.createQuery("insert into Invitation(invited_on, invited_email, invitation_msg, sent_by)");
int result = query.executeUpdate();
}
What is the proper way to insert data? How I should create session Object?
插入数据的正确方法是什么?我应该如何创建会话对象?
回答by Jordi Castilla
You have Hibernate and it's tools USE THEM!!!
你有 Hibernate 和它的工具使用它们!!!
DISCLAIMER:
免责声明:
- Example took from HERE
- code written on the fly!!
- I didnt use
status
attribute because is not mapped!
- 示例取自此处
- 即时编写的代码!!
- 我没有使用
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("[email protected]");
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();
回答by BOUZAR
use this in the main class it works to insert data into table:
在主类中使用它可以将数据插入表中:
Users 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();