当前位置:Gxlcms > mysql > hibernate简单的demo

hibernate简单的demo

时间:2021-07-01 10:21:17 帮助过:32人阅读

mysql表 CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, `pwd` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=10113 DEFAULT CHARSET=utf8; hibernate.cfg.xml ?xml version=

mysql表格

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `pwd` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10113 DEFAULT CHARSET=utf8;

hibernate.cfg.xml








	mysql
	jdbc:mysql://localhost:3306/test
	root
	123456
	com.mysql.jdbc.Driver
	org.hiberna【本文来自鸿网互联 (http://www.68idc.cn)】te.dialect.MySQLDialect
	
	




User.java

package com.domain;

public class User {
	
	Integer id;
	String name;
	String pwd;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
	

}


Test.java

package com.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.domain.*;

public class Test {
	
	public static void main(String[] args) {
		
		Configuration cfg = new Configuration().configure();
		SessionFactory factory = cfg.buildSessionFactory();
		Session session = null;
		
		try{
			session = factory.openSession();
			session.beginTransaction();
			
			User user = new User();
			user.setName("大狼哥");
			user.setPwd("123345");

			session.save(user);
			session.getTransaction().commit();
			
		}catch(Exception e){
			e.printStackTrace();
			session.getTransaction().rollback();
		}finally{
			//关闭session
			if(session != null && session.isOpen())
				session.close();
			}
	}
}


人气教程排行