Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6666637
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T02:50:58+00:00 2026-05-26T02:50:58+00:00

I’ve got a little ‘complex’ question. I’m using Hibernate/JPA to make transactions with a

  • 0

I’ve got a little ‘complex’ question.

I’m using Hibernate/JPA to make transactions with a DB.

I’m not the DBA, and a client consumes my application, a RESTful web service. My problem is that the DB is altered (not very often, but it still changes). Also, the client does not always respect input for my application (length, type, etc.). When this happens Hibernate throws an exception. The exception is difficult to translate and read from the log, because it has nested exceptions and consists of a lot of text: like I said, very difficult to understand.

I want to know if it’s possible to handle exceptions on entity level, throwing maybe a customized exception.

I thank your patience and help in advance.

EDIT:

Fianlly I managed to do what I wanted, not sure if it’s done the right way.

App.java

package com.mc;  

import org.hibernate.Session;  
import com.mc.stock.Stock;  
import com.mc.util.HibernateUtil;  
import javax.persistence.EntityManager;  

public class App {  

    public static void main(String[] args) {  
        Set<ConstraintViolation<Stock>> violations;
        validator = Validation.buildDefaultValidatorFactory().getValidator();
        Scanner scan = new Scanner(System.in);

        EntityManager em = null;

        System.out.println("Hibernate one to many (Annotation)");
        Session session = HibernateUtil.getSessionFactory().openSession();

        session.beginTransaction();


        Stock stock = new Stock();
        String nextLine = scan.nextLine();
        stock.setStockCode(nextLine.toString());
        nextLine = scan.nextLine();
        stock.setStockName(nextLine.toString());


        violations = validator.validate(stock);
        if (violations.size() > 0) {
            StringBuilder excepcion = new StringBuilder();
            for (ConstraintViolation<Stock> violation : violations) {
                excepcion.append(violation.getMessageTemplate());
                excepcion.append("\n");
            }
            System.out.println(excepcion.toString());
        }
        session.save(stock);
        session.getTransaction().commit();
    }  
}  

FieldMatch.java

package com.mc.constraints;  

import com.mc.constraints.impl.FieldMatchValidator;  

import javax.validation.Constraint;  
import javax.validation.Payload;  
import java.lang.annotation.Documented;  
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;  
import static java.lang.annotation.ElementType.TYPE;  
import java.lang.annotation.Retention;  
import static java.lang.annotation.RetentionPolicy.RUNTIME;  
import java.lang.annotation.Target;  

@Target({TYPE, ANNOTATION_TYPE})  
@Retention(RUNTIME)  
@Constraint(validatedBy = FieldMatchValidator.class)  
@Documented  
public @interface FieldMatch {  

    String message() default "{constraints.fieldmatch}";  

    Class<?>[] groups() default {};  

    Class<? extends Payload>[] payload() default {};  

    String first();  

    String second();  

    @Target({TYPE, ANNOTATION_TYPE})  
    @Retention(RUNTIME)  
    @Documented  
    @interface List {  

        FieldMatch[] value();  
    }  
}  

FieldMatchValidator.java

package com.mc.constraints.impl;  

import javax.validation.ConstraintValidator;  
import javax.validation.ConstraintValidatorContext;  
import com.mc.constraints.FieldMatch;  
import org.apache.commons.beanutils.BeanUtils;  

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {  

    private String firstFieldName;  
    private String secondFieldName;  

    @Override  
    public void initialize(final FieldMatch constraintAnnotation) {  
        firstFieldName = constraintAnnotation.first();  
        secondFieldName = constraintAnnotation.second();  
    }  

    @Override  
    public boolean isValid(final Object value, final ConstraintValidatorContext context) {  
        try {  
            final Object firstObj = BeanUtils.getProperty(value, firstFieldName);  
            final Object secondObj = BeanUtils.getProperty(value, secondFieldName);  

            return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);  
        } catch (final Exception ignore) {  
            // ignore  
        }  
        return true;  
    }  
}  

Stock.java

package com.mc.stock;  

import com.mc.constraints.FieldMatch;  
import java.io.Serializable;  
import java.util.HashSet;  
import java.util.Set;  
import javax.persistence.Basic;  
import javax.persistence.Column;  
import javax.persistence.Entity;  
import javax.persistence.GeneratedValue;  
import javax.persistence.GenerationType;  
import javax.persistence.Id;  
import javax.persistence.NamedQueries;  
import javax.persistence.NamedQuery;  
import javax.persistence.OneToMany;  
import javax.persistence.SequenceGenerator;  
import javax.persistence.Table;  
import javax.xml.bind.annotation.XmlRootElement;  
import javax.xml.bind.annotation.XmlTransient;  
import org.hibernate.annotations.Cascade;  
import org.hibernate.annotations.CascadeType;  
import org.hibernate.validator.constraints.Length;  

@Entity  
@Table(name = "STOCK")  
@XmlRootElement  
@NamedQueries({  
    @NamedQuery(name = "Stock.findAll", query = "SELECT s FROM Stock s"),  
    @NamedQuery(name = "Stock.findByStockId", query = "SELECT s FROM Stock s WHERE s.stockId = :stockId"),  
    @NamedQuery(name = "Stock.findByStockCode", query = "SELECT s FROM Stock s WHERE s.stockCode = :stockCode"),  
    @NamedQuery(name = "Stock.findByStockName", query = "SELECT s FROM Stock s WHERE s.stockName = :stockName")})  
@FieldMatch.List({  
    @FieldMatch(first = "stockCode", second = "stockName", message = "Code and Stock must have same value")  
})  
public class Stock implements Serializable {  

    private static final long serialVersionUID = 1L;  
    @Id  
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_stock_id")  
    @SequenceGenerator(name = "seq_stock_id", sequenceName = "seq_stock_id", initialValue = 1, allocationSize = 1)  
    @Basic(optional = false)  
    @Column(name = "STOCK_ID", unique = true, nullable = false)  
    private Integer stockId;  
    @Column(name = "STOCK_CODE")  
    private String stockCode;  
    @Length(min = 1, max = 20, message = "{wrong stock name length}")  
    @Column(name = "STOCK_NAME")  
    private String stockName;  

    public Stock() {  
    }  

    public Stock(Integer stockId) {  
        this.stockId = stockId;  
    }  

    public Integer getStockId() {  
        return stockId;  
    }  

    public void setStockId(Integer stockId) {  
        this.stockId = stockId;  
    }  

    public String getStockCode() {  
        return stockCode;  
    }  

    public void setStockCode(String stockCode) {  
        this.stockCode = stockCode;  
    }  

    public String getStockName() {  
        return stockName;  
    }  

    public void setStockName(String stockName) {  
        this.stockName = stockName;  
    }  

    @Override  
    public int hashCode() {  
        int hash = 0;  
        hash += (stockId != null ? stockId.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 Stock)) {  
            return false;  
        }  
        Stock other = (Stock) object;  
        if ((this.stockId == null && other.stockId != null) || (this.stockId != null && !this.stockId.equals(other.stockId))) {  
            return false;  
        }  
        return true;  
    }  

    @Override  
    public String toString() {  
        return "com.mc.stock.Stock[ stockId=" + stockId + " ]";  
    }  
}  

HibernateUtil.java

package com.mc.util;  

import org.hibernate.SessionFactory;  
import org.hibernate.cfg.Configuration;  

public class HibernateUtil {  

    private static final SessionFactory sessionFactory = buildSessionFactory();  

    private static SessionFactory buildSessionFactory() {  
        try {  
            // Create the SessionFactory from hibernate.cfg.xml  
            return new Configuration().configure().buildSessionFactory();  
        } catch (Throwable ex) {  
            // Make sure you log the exception, as it might be swallowed  
            System.err.println("Initial SessionFactory creation failed." + ex);  
            throw new ExceptionInInitializerError(ex);  
        }  
    }  

    public static SessionFactory getSessionFactory() {  
        return sessionFactory;  
    }  

    public static void shutdown() {  
        // Close caches and connection pools  
        getSessionFactory().close();  
    }  
}  

Oracle DB Structure

CREATE TABLE stock  
(  
    STOCK_ID  NUMBER(5)  NOT NULL ,  
    STOCK_CODE  VARCHAR2(10)  NULL ,  
    STOCK_NAME  VARCHAR2(20)  NULL   
);  

ALTER TABLE stock  
    add CONSTRAINT PK_STOCK_ID  PRIMARY KEY (STOCK_ID);  

create sequence seq_stock_id   
   start with 1   
   increment by 1   
   nomaxvalue;  
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T02:50:58+00:00Added an answer on May 26, 2026 at 2:50 am

    I’m inclined to do as much validation before you get the the DB level. Have a look at Hibernate Validator, http://www.hibernate.org/subprojects/validator.html which is the reference implementation of JSR-303.

    Using standard annotations you can enforce constraints and get good error messages before you attempt to put the entities into your database.

    I believe this will allow you to validate at the entity level as requested.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I've got a string that has curly quotes in it. I'd like to replace
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
i got an object with contents of html markup in it, for example: string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.