Hibernate

Boa tarde

Eu tenho seguinte codigo:

@Entity
@Table(name = "USUARIO")
@NamedQueries({
    @NamedQuery(name = "Usuario.findAll", query = "SELECT u FROM Usuario u")})
public class Usuario implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    @Basic(optional = false)
    @Column(name = "IDUSER")
    private Integer iduser;
    @Basic(optional = false)
    @Column(name = "NOME")
    private String nome;
    @Basic(optional = false)
    @Column(name = "LOGIN")
    private String login;
    @OneToMany(mappedBy = "iduser")
    private List<Referencias> referenciasList = new ArrayList<Referencias>();
    @OneToMany(mappedBy = "iduser")
    private List<CCorrente> cCorrenteList = new ArrayList<CCorrente>();
    @OneToMany(mappedBy = "iduser")
    private List<Relatorios> relatoriosList = new ArrayList<Relatorios>();
    @OneToMany(mappedBy = "iduser")
    private List<Veiculos> veiculosList = new ArrayList<Veiculos>();
    
    
    //RELACIONAMENTOS BIDIRECIONAIS
    @ManyToMany
    @JoinTable(name="CC_USERS", joinColumns=@JoinColumn(name="IDUSER"),
            inverseJoinColumns=@JoinColumn(name="IDCCUSTOS"))
    private List<CentroCustos> ccList = new ArrayList<CentroCustos>();
    
    @ManyToMany
    @JoinTable(name="USER_CARGOS", joinColumns=@JoinColumn(name="IDUSER"),
            inverseJoinColumns=@JoinColumn(name="IDCARGO"))
    private List<Cargos> cargosList = new ArrayList<Cargos>();
    

    public Usuario() {
    }

    public Usuario(Integer iduser) {
        this.iduser = iduser;
    }

    public Usuario(Integer iduser, String nome, String login) {
        this.iduser = iduser;
        this.nome = nome;
        this.login = login;
    }

    public Integer getIduser() {
        return iduser;
    }

    public void setIduser(Integer iduser) {
        this.iduser = iduser;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public List<Referencias> getReferenciasList() {
        return referenciasList;
    }

    public void setReferenciasList(List<Referencias> referenciasList) {
        this.referenciasList = referenciasList;
    }

    public List<CCorrente> getCCorrenteList() {
        return cCorrenteList;
    }

    public void setCCorrenteList(List<CCorrente> cCorrenteList) {
        this.cCorrenteList = cCorrenteList;
    }

    public List<Relatorios> getRelatoriosList() {
        return relatoriosList;
    }

    public void setRelatoriosList(List<Relatorios> relatoriosList) {
        this.relatoriosList = relatoriosList;
    }

    public List<Veiculos> getVeiculosList() {
        return veiculosList;
    }

    public void setVeiculosList(List<Veiculos> veiculosList) {
        this.veiculosList = veiculosList;
    }

    public List<CCorrente> getcCorrenteList() {
        return cCorrenteList;
    }

    public void setcCorrenteList(List<CCorrente> cCorrenteList) {
        this.cCorrenteList = cCorrenteList;
    }

    public List<Cargos> getCargosList() {
        return cargosList;
    }

    public void setCargosList(List<Cargos> cargosList) {
        this.cargosList = cargosList;
    }

    public List<CentroCustos> getCcList() {
        return ccList;
    }

    public void setCcList(List<CentroCustos> ccList) {
        this.ccList = ccList;
    }
    

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (iduser != null ? iduser.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Usuario)) {
            return false;
        }
        Usuario other = (Usuario) object;
        if ((this.iduser == null && other.iduser != null) || (this.iduser != null && !this.iduser.equals(other.iduser))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "br.com.iddeia.entidades.Usuario[ iduser=" + iduser + " ]";
    }
    
}

Como eu poderia fazer uma dao para cadastro desse usuário?

[code]public class HibernateDao implements InterfaceDao {

private Class<T> classe;

public HibernateDao(Class<T> classe) {
	super();
	this.classe = classe;
}	

@Override
public void salvar(T bean) {
	Session session = HibernateUtil.getSf().getCurrentSession();
	session.beginTransaction();
	session.save(bean);
	session.getTransaction().commit();
}

@Override
public void deletar(T bean) {
	Session session = HibernateUtil.getSf().getCurrentSession();
	session.beginTransaction();
	session.delete(bean);
	session.getTransaction().commit();
}

@Override
public void atualizar(T bean) {
	Session session = HibernateUtil.getSf().getCurrentSession();
	session.beginTransaction();
	session.update(bean);
	session.getTransaction().commit();		
}

@Override
public List<T> getBeans() {
	Session session = HibernateUtil.getSf().getCurrentSession();
	session.beginTransaction();
	List<T> beans = (List<T>) session.createCriteria(classe).list();
	session.getTransaction().commit();
	return beans;
}

@Override
public T getBean(Serializable id) {
	Session session = HibernateUtil.getSf().getCurrentSession();
	session.beginTransaction();
	T bean = (T) session.get(classe, id);
	session.getTransaction().commit();
	return bean;
}
[/code]

assim esse é um dao generico na web tem bastante tuturiais de como fazer

Bom Dia

Não querendo ser persistente, mas como implemento o HibernateUtil (para realizar os cadastros)?
E quero ressaltar que o arquivo de configuração é o persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="RelatoriosKMPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
   
    <class>br.com.iddeia.entidades.Permissoes</class>
    <class>br.com.iddeia.entidades.CentroCustos</class>
    <class>br.com.iddeia.entidades.Relatorios</class>
    <class>br.com.iddeia.entidades.Veiculos</class>
    <class>br.com.iddeia.entidades.ContaCorrente</class>
    <class>br.com.iddeia.entidades.Enderecos</class>
    <class>br.com.iddeia.entidades.Cadastro_Clientes</class>
    <class>br.com.iddeia.entidades.Vinculos</class>
    <properties>
      <property name="hibernate.connection.username" value="usuario"/>
      <property name="hibernate.connection.driver_class" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
      <property name="hibernate.connection.password" value="senha"/>
      <property name="hibernate.connection.url" value="jdbc:sqlserver://192.168.5.213\MSSQLSERVER:1433;databaseName=RELATORIOSKM"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
    </properties>
  
  </persistence-unit>
</persistence>

Este é similar ao hibernate.cfg.xml?

pode ser assim


package br.com.projeto.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

	private static final SessionFactory sF;

	public static SessionFactory getSf() {
		return sF;
	}

	static {
		AnnotationConfiguration cfg = new AnnotationConfiguration();
		cfg.configure("hibernate.cfg.xml");
		sF = cfg.buildSessionFactory();
	}
}

Então jovem eu preciso ter os dois arquivos xml:

Persistence.xml e Hibernate.cfg.xml?

não fera… eu so uso o hibernate.cfg.xml nunca usei o persistence.xml unica coisa que muda se não me engana é q o persistence voce colo ele dentro de web inf

Beleza Michelorth entendi perfeitamente.

Contudo eu queria implementar O HibernateDAO e o HibernateUtil, mas eu estou usando o persistence.xml. Como seria com esse arquivo xml?

carra não muda nada só no teu hibernateUtil voce inves de chamar cfg.configure(“hibernate.cfg.xml”); voce vai chamar cfg.configure(“persistence.xml”);

Acesse o meu canal no Youtube. Lá eu tenhos alguns videos sobre Hibernate…

Canal
http://www.youtube.com/user/SerginhoVittorino?feature=mhee

Videos
[youtube]http://www.youtube.com/watch?v=9G5aQxpcjqc&list=UUMpMnEDxXm_jCILYSQx4Mjg&index=4&feature=plcp[/youtube]
[youtube]http://www.youtube.com/watch?v=fgExYbAuagU&feature=related[/youtube]
[youtube]http://www.youtube.com/watch?v=kAYbq9OnTxI&feature=related[/youtube]
[youtube]http://www.youtube.com/watch?v=QF3aVwtbfq0&feature=related[/youtube]

Att.
Serginho Vittorino

Por favor, ao postar tópicos NÃO USE APENAS LETRAS MAIÚSCULAS NO TÍTULO.