我遇到这个问题并且在想你是否可以帮助我解决它。它只是UserLogin和UserProfile之间的简单关系,当UserProfile将其主键作为引用UserProfile主键的外键时。
的persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="PlataformaPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>ptf.model.entities.UserLogin</class>
<class>ptf.model.entities.UserProfile</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/negociacao_db"/>
<property name="javax.persistence.jdbc.user" value="vmribeiro"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="titogzej4"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
</properties>
</persistence-unit>
</persistence>
类
- UserLogin
@Entity
@Table(name = "usuario_login")
public class UserLogin implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_usuario_login")
private long idLogin;
@Column(name = "email_usuario")
private String email;
@Column(name = "senha_usuario")
private String senha;
@Column(name = "tipo_usuario")
private int tipo;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "userLogin")
private UserProfile userProfile;
public UserLogin() {
}
public long getIdLogin() {
return idLogin;
}
public void setIdLogin(long idLogin) {
this.idLogin = idLogin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public int getTipo() {
return tipo;
}
public void setTipo(int tipo) {
this.tipo = tipo;
}
public UserProfile getUserProfile() {
return userProfile;
}
public void setUserProfile(UserProfile userProfile) {
this.userProfile = userProfile;
}
@Override
public String toString() {
return "UserLogin{" + "idLogin=" + idLogin + ", email=" + email + ", senha=" + senha + ", tipo=" + tipo + ", userProfile=" + userProfile + '}';
}
}
- 用户配置
@Entity
@Table(name = "usuario_perfil")
public class UserProfile implements Serializable {
@Id
@Column(name = "id_usuario_perfil")
private long idProfile;
@JoinColumn(name = "id_usuario_login")
@OneToOne
@MapsId
private UserLogin userLogin;
@Column(name = "nome_usuario")
private String nomeUsuario;
@Column(name = "sobrenome_usuario")
private String sobrenomeUsuario;
@Temporal(TemporalType.DATE)
@Column(name = "nasc_usuario")
private Date dtNasc;
@Lob
@Column(length=100000, name = "avatar_usuario")
private byte[] avatar;
@Column(name = "cpf_usuario")
private String cpf;
@Column(name = "rg_usuario")
private String rg;
@Column(name = "estado_usuario")
private String estado;
@Column(name = "cidade_usuario")
private String cidade;
@Column(name = "nota_anunciante")
private double notaAnunciante;
@Column(name = "qtd_negociacoes_anunciante")
private long qtdNegociacoes;
@Column(name = "cep_usuario")
private String cep;
@Column(name = "cel_usuario")
private String cel;
public UserProfile() {
}
public long getIdProfile() {
return idProfile;
}
public void setIdProfile(long idProfile) {
this.idProfile = idProfile;
}
public UserLogin getUserLogin() {
return userLogin;
}
public void setUserLogin(UserLogin userLogin) {
this.userLogin = userLogin;
}
public String getNomeUsuario() {
return nomeUsuario;
}
public void setNomeUsuario(String nomeUsuario) {
this.nomeUsuario = nomeUsuario;
}
public String getSobrenomeUsuario() {
return sobrenomeUsuario;
}
public void setSobrenomeUsuario(String sobrenomeUsuario) {
this.sobrenomeUsuario = sobrenomeUsuario;
}
public Date getDtNasc() {
return dtNasc;
}
public void setDtNasc(Date dtNasc) {
this.dtNasc = dtNasc;
}
public byte[] getAvatar() {
return avatar;
}
public void setAvatar(byte[] avatar) {
this.avatar = avatar;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getRg() {
return rg;
}
public void setRg(String rg) {
this.rg = rg;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public double getNotaAnunciante() {
return notaAnunciante;
}
public void setNotaAnunciante(double notaAnunciante) {
this.notaAnunciante = notaAnunciante;
}
public long getQtdNegociacoes() {
return qtdNegociacoes;
}
public void setQtdNegociacoes(long qtdNegociacoes) {
this.qtdNegociacoes = qtdNegociacoes;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getCel() {
return cel;
}
public void setCel(String cel) {
this.cel = cel;
}
@Override
public String toString() {
return "UserProfile{" + "idProfile=" + idProfile + ", userLogin=" + userLogin + ", nomeUsuario=" + nomeUsuario + ", sobrenomeUsuario=" + sobrenomeUsuario + ", dtNasc=" + dtNasc + ", avatar=" + Arrays.toString(avatar) + ", cpf=" + cpf + ", rg=" + rg + ", estado=" + estado + ", cidade=" + cidade + ", notaAnunciante=" + notaAnunciante + ", qtdNegociacoes=" + qtdNegociacoes + ", cep=" + cep + ", cel=" + cel + '}';
}
}
- UserDAO的
class UserDAO implements IUserDAO {
public EntityManagerFactory emf;
private EntityManager getEntityManager() {
emf = Persistence.createEntityManagerFactory("PlataformaPU");
return emf.createEntityManager();
}
@Override
public boolean save(UserLogin ul) {
boolean result = false;
EntityManager em = getEntityManager();
try {
em.getTransaction().begin();
if (ul.getIdLogin() == 0) {
//If this entity does not exist, insert
em.persist(ul);
result = true;
} else {
if (!em.contains(ul)) {
//If this entity has to exist but was not found in db, error
if (em.find(UserLogin.class, ul.getIdLogin()) == null) {
throw new Exception("Erro ao atualizar o login!");
}
}
//If this entity exists and can be found in db, update
em.merge(ul);
em.flush();
result = true;
}
em.getTransaction().commit();
} catch (Exception ex) {
em.getTransaction().rollback();
ex.printStackTrace();
result = false;
} finally {
em.clear();
em.close();
emf.close();
}
return result;
}
@Override
public boolean remove(long id) {
boolean result = false;
EntityManager em = getEntityManager();
UserLogin ul = em.find(UserLogin.class, id);
try {
em.getTransaction().begin();
em.remove(ul);
em.getTransaction().commit();
result = true;
} finally {
em.clear();
em.close();
emf.close();
}
return result;
}
@Override
public UserLogin findById(long id) {
UserLogin result = null;
EntityManager em = getEntityManager();
try {
result = em.find(UserLogin.class, id);
} finally {
em.clear();
em.close();
emf.close();
}
return result;
}
@Override
public List<UserLogin> findAll() {
EntityManager em = getEntityManager();
List<UserLogin> result = null;
try {
Query q = em.createQuery("select u from UserLogin u");
result = q.getResultList();
} finally {
em.clear();
em.close();
emf.close();
}
return result;
}
@Override
public UserLogin findByEmail(String email, String senha) {
EntityManager em = getEntityManager();
UserLogin result = null;
try {
Query q = em.createQuery("select u from UserLogin u where u.email=:email");
q.setParameter("email", email);
result = (UserLogin) q.getSingleResult();
}catch (NoResultException ex){
//I'll be defined a message on controller when it's null
result = null;
}
finally {
em.clear();
em.close();
emf.close();
}
return result;
}
}
- 我用来测试的主要课程。
public class PlataformaNegociacaoBase {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
UserProfile up = new UserProfile();
up.setAvatar(null);
up.setCel("12314141");
up.setCep("12312-13");
up.setCidade("São Paulo");
up.setCpf("2141123");
try {
up.setDtNasc(df.parse("21/11/1997"));
} catch (ParseException ex) {
Logger.getLogger(PlataformaNegociacaoBase.class.getName()).log(Level.SEVERE, null, ex);
}
up.setEstado("SP");
up.setNomeUsuario("Joao");
up.setNotaAnunciante(0);
up.setQtdNegociacoes(0);
up.setRg("234142512");
up.setSobrenomeUsuario("Pedro");
UserLogin ul = new UserLogin();
ul.setEmail("joao@joao.com");
ul.setSenha("123");
ul.setTipo(1);
up.setUserLogin(ul);
ul.setUserProfile(up);
IUserDAO uld = DAOFactory.getUserLoginDAO();
// ul = (UserLogin) uld.findById(3);
// System.out.println(ul);
// ul.setEmail("jonas@alter.com");
// ul.setSenha("alterjonas");
System.out.println(uld.save(ul));
// System.out.println(uld.remove(3));
// List<UserLogin> all = (ArrayList<UserLogin>)uld.findAll();
// all.forEach((userLogin) -> {
// System.out.println(userLogin);
// });
}
}
错误:
Exception in thread "main" java.lang.IllegalStateException: Transaction not active
at org.hibernate.jpa.internal.TransactionImpl.rollback(TransactionImpl.java:105)
at ptf.model.dao.UserDAO.save(UserDAO.java:50)
at ptf.model.dao.UserDAO.save(UserDAO.java:15)
at ptf.test.PlataformaNegociacaoBase.main(PlataformaNegociacaoBase.java:58)
C:\Users\Victor Ribeiro\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
答案 0 :(得分:0)
当UserProfile将主键作为引用UserProfile主键的外键时,UserLogin和UserProfile之间只是一个简单的关系
我不明白这一点,但我可以给你一些建议。
首先,要解决您的任务,您应该使用@PrimaryKeyJoinColumn
最好使用
private Long idLogin;
你有复杂的方法save(UserLogin ul)
只是扔掉所有这些垃圾并简单地使用它。
我认为您可以将merge()
与Long idLogin
一起使用。如果您需要检查是否存在idLogin
- 方法save()
不是一个好地方。