Data Truncation with Hibernate

Asked

Viewed 245 times

4

Goodnight.

I have a problem to persist an object, Hibernate throws an exception saying that the data are too long for the "street" column, type String.

Follow Pojos and DAO.

Address

@Embeddable
public class Endereco implements Serializable {

    private String cidade;
    private String estado;
    private String rua;
    private String numero;
    private String complemento;

//Gets, Sets, Hash e Equals

Pupil

@Entity
@Table(name="Aluno", schema="IFBC")
public class Aluno implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int idAluno;

    private int matricula;
    private int rg;

    private String nome;
    private String nomePai;
    private String nomeMae;
    private String naturalidade;
    private String orgaoExpedRG;
    private String obsAlergia;
    private String obsDoencaCronica;
    private String email;
    private String obs;
    private String cpf;

    private boolean possuiDoencaCronica;
    private boolean menorDeIdade;
    private boolean terminouCurso;
    private boolean possuiAlergia;

    @Temporal(javax.persistence.TemporalType.DATE)
    private Date dataInicioCurso;

    @Temporal(javax.persistence.TemporalType.DATE)
    private Date dataTerminoCurso;

    @Temporal(javax.persistence.TemporalType.DATE)
    private Date dataNascimento;

    private long telefone;

    private char sexo;

    @Embedded
    private Endereco endereco;

    @OneToOne
    @JoinColumn(name="idTurma")
    private Turma turma;

    @OneToOne
    @JoinColumn(name="idUsuario")
    private Usuario cadastrante; //Quem cadastrou

    private boolean formado;

DAO

public class Dao {

    private Session session;
    private Transaction transaction;

    public Dao() {

    }

    private void iniciarOperacao() {
        session = HibernateUtil.getSessionFactory().openSession();
        transaction = session.beginTransaction();
    }

    private void terminarOperacao() {
        if(session != null) 
            session.close();
    }

    public boolean salvar(Object ob) {
        try {
            iniciarOperacao();
            session.saveOrUpdate(ob);
            transaction.commit();
            return true;
        } catch (Exception e) {
            transaction.rollback(); 
            e.printStackTrace();
        } finally {
            terminarOperacao();
        }
        return false;
    }

    public boolean excluir(Object obj) {
        try {
            iniciarOperacao();
            session.delete(obj);
            transaction.commit();
            return true;
        } catch(Exception e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            terminarOperacao();
        }
        return false;
    }

    public <T> T buscar(Class cls, int id) {
        T obj = null;

        try {
            iniciarOperacao();
            obj = (T) session.load(cls, id);
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            terminarOperacao();
        }

        return obj;
    }

    public List listar(Class cls) {
        try {
            iniciarOperacao();
            Criteria criteria = session.createCriteria(cls);
            List list = criteria.list();
            transaction.commit();

            return list;
        } catch (Exception e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            terminarOperacao();
        }

        return null;
    }

Exception

org.hibernate.exception.DataException: could not insert: [br.com.ifbc.model.pojo.Aluno]
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:102)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2329)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2836)
    at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
    at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:267)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:117)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:677)
    at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:669)
    at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:665)
    at br.com.ifbc.control.dao.Dao.salvar(Dao.java:33)
    at br.com.ifbc.view.aluno.CadastrarAluno.btnCadastrarActionPerformed(CadastrarAluno.java:496)
    at br.com.ifbc.view.aluno.CadastrarAluno.access$000(CadastrarAluno.java:14)
    at br.com.ifbc.view.aluno.CadastrarAluno$1.actionPerformed(CadastrarAluno.java:109)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6516)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6281)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4872)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:747)
    at java.awt.EventQueue.access$300(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:706)
    at java.awt.EventQueue$3.run(EventQueue.java:704)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:720)
    at java.awt.EventQueue$4.run(EventQueue.java:718)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:717)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:154)
    at java.awt.WaitDispatchSupport$2.run(WaitDispatchSupport.java:182)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSupport.java:221)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.WaitDispatchSupport.enter(WaitDispatchSupport.java:219)
    at java.awt.Dialog.show(Dialog.java:1082)
    at java.awt.Component.show(Component.java:1655)
    at java.awt.Component.setVisible(Component.java:1607)
    at java.awt.Window.setVisible(Window.java:1014)
    at java.awt.Dialog.setVisible(Dialog.java:1005)
    at br.com.ifbc.view.aluno.CadastrarAluno$5.run(CadastrarAluno.java:564)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:312)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:745)
    at java.awt.EventQueue.access$300(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:706)
    at java.awt.EventQueue$3.run(EventQueue.java:704)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:715)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'rua' at row 1
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3489)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2542)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1734)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2019)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1937)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1922)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
    ... 75 more

The error would be caused by @Embeddable? This is the first time I’ve worked with this.

Thanks in advance!

1 answer

3

The error message leaves no doubt: the system is trying to enter the record in the database, but is sending more characters in the field rua than fits in that field.

Your entity does not specify the size of the fields, so there is no way of knowing the size of the field rua. I also don’t know if the system is generating tables based on Hibernate or if the bank is created in some other way.

If you use Hibernate to generate the tables, I strongly suggest you specify the size of each String column. Example:

@Column(length = 10) 
private String rua;

Otherwise, all fields will be created with the standard 255 characters, which is not cool in a modeling.

If, on the other hand, the database is created by another process, check the table or script that creates the table for the size of the field rua.

It would be interesting to add data validation annotations to avoid these strange errors. See, for example, the Hibernate Validator.

Finally, check the size of the string being placed on the object Endereco. Probably the system is allowing the user to type a street larger than the table size, or is still importing data from somewhere, such as a text file, and does not check whether the data size fits in the table.

With all this information, you will have to make the decision on how to solve the problem, whether by increasing the size of the table field, cutting the entered data, limiting user input, etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.