hibernate组件映射

hibernate组件映射也就是包含映射,关系犹如汽车(Car)与车轮(Wheel)

1、创建实体类Wheel.java

package cn.itcast.a;

public class Wheel {
	private int count;
	private int size;
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public int getSize() {
		return size;
	}
	public void setSize(int size) {
		this.size = size;
	}
	
}

2、创建实体类Car.java

package cn.itcast.a;

public class Car {
	private int id;
	private String name;
	private Wheel wheel;
	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 Wheel getWheel() {
		return wheel;
	}
	public void setWheel(Wheel wheel) {
		this.wheel = wheel;
	}
	
}

3、配置Car.hbm.xml





	
	
		
		
		
			
			
		
		
				
		
		
			
			
		
	

4、配置hibernate.cfg.xml




	
		true
		
		com.mysql.jdbc.Driver
		jdbc:mysql:///employee
		root
		123456
		org.hibernate.dialect.MySQL5Dialect
		
		
		true
				
		true
		
		update
		
		
	

5、创建测试类App.java

package cn.itcast.a;

import static org.junit.Assert.*;

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

public class App {
	private static SessionFactory sf;
	static{
		sf=new Configuration()
			.configure()
			.buildSessionFactory();
	}
	@Test
	public void test() {
		Session session=sf.openSession();
		session.beginTransaction();
		
		Wheel wheel=new Wheel();
		wheel.setSize(40);
		wheel.setCount(4);
		
		Car car=new Car();
		car.setName("奔驰");
		car.setWheel(wheel);
		

		session.save(car);
		
		session.getTransaction();
		session.close();
	}

}



你可能感兴趣的:(hibernate)