Estou tentando fazer usando as classes abaixo não programo em java já tem 7 anos estou em outro ramo de agropecuária … mas quero fazer um sistema em java simples para poder usar.
Model
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
@Entity
@Table(name = “acesso”)
//@Cacheable
//@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Acesso implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(nullable = false, length = 50)
private String email;
@Column(nullable = false, length = 8)
private String senha;
//@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@OneToOne
@JoinColumn(name = "idPessoa", nullable = false, insertable = false, updatable = false)
@Fetch(FetchMode.JOIN)
private Pessoa pessoa;
public Acesso() {
}
@Override
public String toString() {
return email;
}
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 Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((senha == null) ? 0 : senha.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Acesso other = (Acesso) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (senha == null) {
if (other.senha != null)
return false;
} else if (!senha.equals(other.senha))
return false;
return true;
}
}
Bean
import hibernate.GenericWorker;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import modelo.Acesso;
import modelo.Pessoa;
@SuppressWarnings(“serial”)
@ManagedBean(name = “acessoBean”)
@SessionScoped
public class AcessoBean implements Serializable {
private String email;
private String senha;
private String mensagemUsuario;
private Acesso acesso;
private Pessoa pessoa;
public AcessoBean() {
super();
this.acesso = new Acesso();
this.pessoa = this.acesso.getPessoa();
this.email = "";
this.senha = "";
this.mensagemUsuario = "";
}
public String login() {
try {
GenericWorker<Acesso, String> regHBR2 = new GenericWorker<Acesso, String>(
Acesso.class);
acesso = (Acesso) regHBR2.consulta(this.email);
regHBR2.finalize();
pessoa = acesso.getPessoa();
if (email.equals(acesso.getEmail())
&& senha.equals(acesso.getSenha())) {
this.mensagemUsuario = "";
return "sucesso";
} else {
this.mensagemUsuario = "Dados inválidos.";
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "ERRO!",
"Dados inválidos."));
return "insucesso";
}
} catch (Exception e) {
this.mensagemUsuario = "Dados não conferem.";
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "ERRO!", "Dados inválidos."));
e.printStackTrace();
}
return "insucesso";
}
public String logout() {
this.acesso = new Acesso();
this.pessoa = this.acesso.getPessoa();
this.email = "";
this.senha = "";
this.mensagemUsuario = "";
return "insucesso";
}
public boolean isValid() {
try {
GenericWorker<Acesso, String> regHBR2 = new GenericWorker<Acesso, String>(
Acesso.class);
acesso = (Acesso) regHBR2.consulta(this.email);
regHBR2.finalize();
if (email.equals(acesso.getEmail())
&& senha.equals(acesso.getSenha())) {
return true;
}
} catch (Exception e) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_ERROR, "ERRO!", "Dados inválidos."));
e.printStackTrace();
}
return false;
}
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 String getMensagemUsuario() {
return mensagemUsuario;
}
public void setMensagemUsuario(String mensagemUsuario) {
this.mensagemUsuario = mensagemUsuario;
}
public Pessoa getPessoa() {
return pessoa;
}
public void setPessoa(Pessoa pessoa) {
this.pessoa = pessoa;
}
}
Dao
import java.io.Serializable;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.Session;
import org.hibernate.StaleStateException;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.exception.ConstraintViolationException;
public class GenericWorker<T, ID extends Serializable> implements
InterfaceWorker<T, ID> {
private Session session;
public Class entidade;
public GenericWorker(Class<T> entidade) {
//Abre uma sessão nova.
session = SessaoFactory.getSessionFactory().openSession();
//Abre uma sessão existente. Melhor que openSession se já existir.
//session = SessaoFactory.getSessionFactory().getCurrentSession();
this.entidade = entidade;
}
@Override
public void finalize() {
if (session != null) {
session.flush();
session.clear();
session.close();
}
try {
super.finalize();
} catch (Throwable e) {
e.printStackTrace();
}
}
public boolean inclui(T registro) throws HibernateException,
ConstraintViolationException {
Transaction tx = session.beginTransaction();
try {
session.save(registro);
tx.commit();
} catch (ConstraintViolationException e) {
if (tx != null)
tx.rollback();
throw new ConstraintViolationException(
"Falha de inclusão: Objeto já existe.", null,
"Registro duplicado.");
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw new HibernateException("Falha de inclusão no BD: ", e);
} finally {
//session.close();
}
return true;
}
public boolean exclui(T registro) throws HibernateException,
ObjectNotFoundException {
Transaction tx = session.beginTransaction();
try {
session.delete(registro);
tx.commit();
} catch (ObjectNotFoundException e) {
if (tx != null)
tx.rollback();
throw new ObjectNotFoundException(
"Falha de consulta: Objeto não localizado.",
"ERRO! Objeto não localizado");
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw new HibernateException("Falha de exclusão no BD: ", e);
} finally {
//session.close();
}
return true;
}
public boolean altera(T registro) throws HibernateException,
ObjectNotFoundException {
Transaction tx = session.beginTransaction();
try {
session.update(registro);
tx.commit();
} catch (StaleStateException e) {
if (tx != null)
tx.rollback();
throw new ObjectNotFoundException(
"Falha de consulta: Objeto não localizado ",
"ERRO! Objeto não localizado");
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
throw new HibernateException("Falha de alteração no BD: ", e);
} finally {
//session.close();
}
return true;
}
public Object consulta(ID id) throws HibernateException,
ObjectNotFoundException {
Object registro;
try {
registro = session.get(entidade, id);
} catch (ObjectNotFoundException e) {
throw new ObjectNotFoundException(
"Falha de consulta: Objeto não localizado ",
"ERRO! Objeto não localizado");
} catch (HibernateException e) {
throw new HibernateException("Falha de consulta no BD: ", e);
} finally {
//session.close();
}
return registro;
}
@SuppressWarnings("unchecked")
public List<T> listar(int inicio, int quantia) throws HibernateException {
List<T> listagem;
try {
listagem = session.createCriteria(entidade).setMaxResults(quantia)
.setFirstResult(inicio).list();
} catch (HibernateException e) {
throw new HibernateException("Falha de consulta no BD: ", e);
} finally {
//session.close();
}
return listagem;
}
@SuppressWarnings("unchecked")
public List<T> listar(Criterion clausula[]) throws HibernateException {
List<T> listagem;
try {
switch (clausula.length) {
case 1:
listagem = session.createCriteria(this.entidade)
.add(clausula[0]).list();
break;
case 2:
listagem = session.createCriteria(this.entidade)
.add(clausula[0]).add(clausula[1]).list();
break;
case 3:
listagem = session.createCriteria(this.entidade)
.add(clausula[0]).add(clausula[1]).add(clausula[2])
.list();
break;
case 4:
listagem = session.createCriteria(this.entidade)
.add(clausula[0]).add(clausula[1]).add(clausula[2])
.add(clausula[3]).list();
break;
case 5:
listagem = session.createCriteria(this.entidade)
.add(clausula[0]).add(clausula[1]).add(clausula[2])
.add(clausula[3]).add(clausula[4]).list();
break;
default:
listagem = session.createCriteria(this.entidade).list();
}
} catch (HibernateException e) {
throw new HibernateException("Falha de consulta no BD: ", e);
} finally {
//session.close();
}
return listagem;
}
}