1,导入hibernate 的jar包,c3p0jar包
2,创建和表关联的实体类,创建关联实体类的配置文件
package com.entity; public class News { private Integer id; private String title; private String content; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.entity"> <class name="News" table="news_table"> <id name="id"><generator class="identity"/></id> <property name="title"/> <property name="content"/> </class> <!-- <class name="Parent"> <id name="name"/> <list name="children" fetch="subselect" cascade="persist, delete"> <key column="parentName" not-null="true"/> <list-index column="loc"/> <one-to-many class="Child"/> </list> <list name="moreChildren" table="ParentChild" fetch="subselect"> <key column="parentName" not-null="true"/> <list-index column="loc"/> <many-to-many class="Child" column="childName"/> </list> </class> --> </hibernate-mapping>
然后吗,自己看注释去...
package com.hirbernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.entity.News; public class NewsManager { @SuppressWarnings("deprecation") public static void main(String[] args) { //默认加载src下hibernate.cfg.xml文件,不行就自己另行指定,我还是自己来吧 Configuration configuration = new Configuration().configure("config/hibernate.cfg.xml"); //用configuration创建SessionFactory SessionFactory sessionFactory = configuration.buildSessionFactory(); //创建session Session session =sessionFactory.openSession(); //开始事务 Transaction trans = session.beginTransaction(); //创建消息实例 News news = new News(); //设置实例值 news.setTitle("ddd"); news.setContent("ddddd"); session.save(news); //提交当前事务 trans.commit(); //关闭session session.close(); //关闭sessionfactory sessionFactory.close(); } }