Hibernate简单配置
1.配置构建路径,加载用户库,hibernate4.3.8 MySQL-Driver
2.写User.java 纯POJO+持久化注解=PO
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
...
3.配置hibernate.cfg.cml
<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="hbm2ddl.auto">update</property> <property name="show_sql">true</property> <mapping class="org.crazyit.app.domain.User"/> </session-factory> </hibernate-configuration>
4.调用即可创建数据库表并更新记录
public static void main(String[] args)
throws Exception
{
// 实例化Configuration,
Configuration conf = new Configuration()
// 不带参数的configure()方法默认加载hibernate.cfg.xml文件,
// 如果传入abc.xml作为参数,则不再加载hibernate.cfg.xml,改为加载abc.xml
.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(conf.getProperties()).build();
// 以Configuration实例创建SessionFactory实例
SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
// 创建Session
Session sess = sf.openSession();
// 开始事务
Transaction tx = sess.beginTransaction();
// 创建消息对象
User u=new User();
u.setUsername("dddd");
u.setPassword("iiiiii");
// 保存消息
sess.save(u);
sess.save(n);
// 提交事务
tx.commit();
// 关闭Session
sess.close();
sf.close();
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。