Hibernate系列(一):简单的数据插入
第一步,我们需要写一个POJO类:User.java
package cn.itcast.hibernate.domain; import java.util.Date; public class User { private int id; private String name; private Date birthday; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }为了使这个javabean具有持久化操作的能力,我们需要在当前包下添加一个映射文件User.hbm.xml:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.itcast.hibernate.domain"> <class name="User" table="tb_User"> <id name="id"> <generator class="native"/> </id> <property name="name" /> <property name="birthday" /> </class> </hibernate-mapping>
<?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"> <hibernate-configuration> <session-factory> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="connection.url"> jdbc:mysql://localhost:3306/test </property> <property name="connection.username">sa</property> <property name="connection.password">123456</property> <property name="hbm2ddl.auto">create</property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <mapping resource="cn/itcast/hibernate/domain/User.hbm.xml" /> </session-factory> </hibernate-configuration>
最后,我们写一个简单的Main类来实现简单的数据插入Base.java:
package cn.itcast.hibernate; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import cn.itcast.hibernate.domain.User; public class Base { public static void main(String[] args) { Configuration cfg = new Configuration(); //生成一个Configuration对象 cfg.configure(); //调用configure()方法加载映射文件 SessionFactory sf = cfg.buildSessionFactory(); //产生一个SessionFactory Session s = sf.openSession(); //开启session Transaction tx = s.beginTransaction(); //开启事务 User user = new User(); user.setBirthday(new Date()); user.setName("name"); s.save(user); //把user对象保存在session中 tx.commit(); //提交事务 s.close(); //关闭session System.out.println("end"); } }
运行就可以实现简单的数据插入了。
需要用到的jar包:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。