2015-09-07 3 views
0

У меня есть 2 Mysql таблицы пользователей и империи, пользователейJPA One_to_One отношений не получить автоматическое приращение

CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
`email` varchar(45) CHARACTER SET utf8 NOT NULL, 
`password` varchar(12) CHARACTER SET utf8 NOT NULL, 
`country` varchar(25) CHARACTER SET utf8 NOT NULL, 
`activated` tinyint(3) unsigned NOT NULL DEFAULT '0', 
`activationcode` varchar(45) CHARACTER SET utf8 NOT NULL DEFAULT '', 
PRIMARY KEY (`id`), 
UNIQUE KEY `email_UNIQUE` (`email`), 
KEY `email` (`email`) 
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 

и империи

CREATE TABLE `empires` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
`pid` int(10) unsigned NOT NULL, 
`name` varchar(45) CHARACTER SET utf8 NOT NULL, 
`notes` varchar(90) CHARACTER SET utf8 NOT NULL, 
`world` tinyint(3) unsigned NOT NULL, 
`island` smallint(5) DEFAULT NULL, 
`population` int(10) unsigned DEFAULT '20', 
`gold` decimal(20,0) DEFAULT '500', 
`percent` decimal(9,5) DEFAULT '50.00000', 
`logo` varchar(30) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', 
PRIMARY KEY (`id`,`pid`), 
KEY `name` (`name`), 
KEY `world` (`world`), 
KEY `FK_pid` (`pid`) 
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 

и у меня есть эти объекты:

package boddooo.entity; 

import java.io.Serializable; 
import javax.persistence.*; 

@Entity 
@Table(name="users") 
@NamedQuery(name="User.findAll", query="SELECT u FROM User u") 
public class User implements Serializable { 
private static final long serialVersionUID = 1L; 

@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY) 
private int id; 
private int activated=1; 
private String activationcode=""; 
private String country; 
private String email; 
private String password; 

public User(){} 
public User(int id,String email,String password,String country) { 
    this.id=id; 
    this.email=email; 
    this.password=password; 
    this.country=country; 
} 

public int getId() { 
    return this.id; 
} 

public void setId(int id) { 
    this.id = id; 
} 

public int getActivated() { 
    return this.activated; 
} 

public void setActivated(int activated) { 
    this.activated = activated; 
} 

public String getActivationcode() { 
    return this.activationcode; 
} 

public void setActivationcode(String activationcode) { 
    this.activationcode = activationcode; 
} 

public String getCountry() { 
    return this.country; 
} 

public void setCountry(String country) { 
    this.country = country; 
} 

public String getEmail() { 
    return this.email; 
} 

public void setEmail(String email) { 
    this.email = email; 
} 

public String getPassword() { 
    return this.password; 
} 

public void setPassword(String password) { 
    this.password = password; 
} 

} 

и

package boddooo.entity; 

import java.io.Serializable; 
import java.math.BigDecimal; 

import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.NamedQuery; 
import javax.persistence.OneToOne; 
import javax.persistence.PrimaryKeyJoinColumn; 
import javax.persistence.Table; 

@Entity 
@Table(name="empires") 
@NamedQuery(name="Empire.findAll", query="SELECT e FROM Empire e") 
public class Empire implements Serializable { 
private static final long serialVersionUID = 1L; 

@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY) 
private int id; 

private int pid; 
private BigDecimal gold=BigDecimal.valueOf(500); 
private String logo=""; 
private String name; 
private String notes; 
private BigDecimal percent=BigDecimal.valueOf(50.0000); 
private int population=10; 
private int world; 
private int island; 

@OneToOne 
@PrimaryKeyJoinColumn(name="pid") 
private User user; 

public User getUser() { 
    return user; 
} 

public void setUser(User user) { 
    this.user = user; 
} 

public Empire(){} 
public Empire(int id,String name,String logo,String notes,int world) { 
    this.id=id; 
    this.name=name; 
    this.logo=logo; 
    this.notes=notes; 
    this.world=world; 
} 

public int getPid() { 
    return pid; 
} 
public void setPid(int pid){ 
    this.pid=pid; 
} 

public int getWorld() { 
    return world; 
} 

public void setWorld(int world) { 
    this.world = world; 
} 

public int getIsland() { 
    return island; 
} 

public void setIsland(int island) { 
    this.island = island; 
} 

public int getId() { 
    return this.id; 
} 

public void setId(int id) { 
    this.id = id; 
} 

public BigDecimal getGold() { 
    return this.gold; 
} 

public void setGold(BigDecimal gold) { 
    this.gold = gold; 
} 

public String getLogo() { 
    return this.logo; 
} 

public void setLogo(String logo) { 
    this.logo = logo; 
} 

public String getName() { 
    return this.name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public String getNotes() { 
    return this.notes; 
} 

public void setNotes(String notes) { 
    this.notes = notes; 
} 

public BigDecimal getPercent() { 
    return this.percent; 
} 

public void setPercent(BigDecimal percent) { 
    this.percent = percent; 
} 

public int getPopulation() { 
    return this.population; 
} 

public void setPopulation(int population) { 
    this.population = population; 
} 
} 

и эта функция, чтобы вставить новые OBJETS в базу данных

public void createUser() throws NamingException, NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException{ 
    Context icontext=new InitialContext(); 
    ut=(UserTransaction)icontext.lookup("java:comp/UserTransaction"); 
    ut.begin(); 
    User user=new User(); 
    user.setEmail(email); 
    user.setPassword(password); 
    user.setCountry(country); 
    em.persist(user); 
    Empire emp=new Empire(); 
    emp.setName(empirename); 
    emp.setNotes(empirenotes); 
    emp.setLogo(empirelogo); 
    emp.setWorld(worldid); 
    emp.setUser(user); 
    em.persist(emp); 
    ut.commit(); 
} 

это отношение один к одному, который empires.pid = users.id но когда я называю этот метод его вставкой пользователей и империй но поле pid в empires имеет значение 0 вместо значения автоматического приращения. Я что-то пропустил? пожалуйста, помогите

ответ

0

@PrimaryKeyJoinColumn указывает, что поле используется для этого первичного ключа сущностей и как таковое эффективно доступно только для чтения. Это чаще всего используется, когда у вас есть объект, который охватывает несколько таблиц. @JoinColumn - это то, что вы должны использовать, поскольку он указывает, что указанный столбец является традиционным внешним ключом и что вы хотите, чтобы целевое значение использовалось для установки этого поля.

@OneToOne 
@JoinColumn(name="pid") 
private User user; 
+0

и pid должны быть доступны только для чтения, спасибо – Mohamed

Смежные вопросы