简体   繁体   中英

Insertion of rows with primary key/foreign key using Hibernate

In my Spring project, I am trying insert some rows in the database, using Hibernate, but I am facing two problems:

1) In one of the tables, represented by this class:

@Entity
@Table(name="sessao")
public class Sessao implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @Column
    private int id;

    @Column
    private Usuario usuario;

    @Column
    private int action;

    public Sessao() {
    }

    public Sessao(Usuario usuario, int action) {
        this.usuario = usuario;
        this.action = action;
    }

    public Sessao(int id, Usuario usuario, int action) {
        this.id = id;
        this.usuario = usuario;
        this.action = action;
    }

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

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

    public Usuario getUsuario() {
        return this.usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    public int getAction() {
        return this.action;
    }

    public void setAction(int action) {
        this.action = action;
    }
}

The columns Usuario is a foreign key to table of same name in the database. When I try insert one item in the database, in this way:

Usuario novo = new Usuario(username, convertByteToHex(digest));
List<Usuario> lista = (List<Usuario>) usuario.findByExample(novo);
novo.setId(lista.get(0).getId());
        novo.setPnome(lista.get(0).getPnome());
        novo.setUnome(lista.get(0).getUnome());
        this.setId_usuario(novo.getId());

        if(lista.size() == 0) {
            ModelAndView mav = new ModelAndView();
            mav.setViewName("usuario_login");
            return mav;
        }
        else {
            Sessao nova = new Sessao(novo, 0);
            sessao.persist(nova);
            ModelAndView mav = new ModelAndView();
            mav.setViewName("usuario_start");
            mav.addObject("usuario", novo);
            return mav;
        }

I am receiving the error message:

ERROR: null value in column "fk_usuario" violates not-null constraint

Someone knows how to solve this?

2) The other situation is related to primary key, whom in the database is represented by the type serial , so when I do an insert, I don't need inform this field, and can do this way:

INSERT INTO sessao(fk_usuario, action, usuario) VALUES (?, ?, ?);

my other question is: all my Model classes have construtors where I don't need pass the Id as parameter. If I have created an Object with this construtor, how I could pass this object for my DAO class to save it in the database.

the method resposable for saving the data in the database in my DAO class is:

@Transactional
public void persist(Sessao transientInstance) {
    log.debug("persisting Sessao instance");
    try {
        sessionFactory.getCurrentSession().persist(transientInstance);
        log.debug("persist successful");
    } catch (RuntimeException re) {
        log.error("persist failed", re);
        throw re;
    }
}

The code should map an association between the Usario entity and the Sessao entity.

public class Sessao{
    @OneToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="FORIEGN_KEY_HERE")
    private Usuario usuario;
}

I am assuming this relationship is a One to One I would suggest watching a video tutorial I have created about mapping @OneToOne associations.

To solve the issue with the primary keys use the @GeneratedValue annotation and specify a strategy:

@Id
@Column
@GeneratedValue(strategy=GenerationType.AUTO) //May need to adjust this to a different strategy
private int id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM