Java_cpp_
天使中的魔鬼M
2021-01-24 15:04

采用@GeneratedValue自动生成Id,两张表的id为什么不都是从1开始

  • hibernate


@Entity
@Table(name="t_group")
public class Group {
	private int id;
	private String name;
	private Set<User> users = new HashSet<User>();
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	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;
	}
	@OneToMany
	
	public Set<User> getUsers() {
		return users;
	}
	public void setUsers(Set<User> users) {
		this.users = users;
	}
}

@Entity
@Table(name="t_user")
public class User {
	private int id;
	private String name;
	private Group group;
	@ManyToOne(cascade={CascadeType.ALL})
	public Group getGroup() {
		return group;
	}
	public void setGroup(Group group) {
		this.group = group;
	}
	@Id
	@GeneratedValue
	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;
	}
}

//测试方法
@Test
	public void testSaveUser() {
		User u = new User();
		u.setName("u1");
		Group g = new Group();
		g.setName("g1");
		
		u.setGroup(g);
		
		Session session = sf.openSession();
		session.beginTransaction();
		session.save(u);;
		session.getTransaction().commit();
		session.close();
		
	}

查看生成的两张表的id

采用@GeneratedValue自动生成Id策略为什么两张表生成的id是顺序接连下来的,而不是从1各自递增?

Hibernate版本:hibernate-release-5.2.17.Final

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答