Hibernate 修改数据库

hibernate.cfg.xml







    
        org.hibernate.dialect.MySQLDialect
        jdbc:mysql://192.168.137.113:3306/stu
        root
        ROOT
        com.mysql.jdbc.Driver
        firstTest
    	true
    	true
    	
    	
    	
    

Student.java 学生类

package cn.com.edu;


import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;

@Entity
public class Student {
	@Id
	@GenericGenerator(name = "generator", strategy = "increment")
	@GeneratedValue(generator = "generator")
	private int id;
	
	private String name;
	private String sex;
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(int id, String name, String sex) {
		super();
		this.id = id;
		this.name = name;
		this.sex = sex;
	}
	public Student(String name, String sex) {
		super();
		this.name = name;
		this.sex = sex;
	}
	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 String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
}

hiberTest.java

package cn.com.edu;

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




public class hiberTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Configuration con=new Configuration().configure();//读取解析配置文件
		SessionFactory sf=con.buildSessionFactory(); //创建工厂,读取映射信息
		
		Session session=sf.openSession();//打开Session
		
		Student s = function1(session);//修改信息

		Transaction tr=session.beginTransaction(); //创建并开始一个事务
		session.save(s);
		tr.commit();
		session.close();
		sf.close();
	}

	public static Student function1(Session session){
		Student s1=(Student)session.get(Student.class, 2);
		s1.setName("laji");
		s1.setSex("人妖");
		return s1;
	}

}

 

你可能感兴趣的:(Java学习)