0

I know this has been asked many times, but none of the answers have solved the problem so far.

My code was working perfectly for years up until I upgraded from Hibernate 4.3.11 to Hibernate 5.2.0. Now I'm getting the following error:

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [select password, salt from User where userName=:fullName and distributor_id is null]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:131)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:633)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:101)
at com.stuhrling.service.authentication.AuthenticationService.authenticate(AuthenticationService.java:103)
at com.stuhrling.service.authentication.AuthenticationService.processLogin(AuthenticationService.java:42)
at com.stuhrling.interceptor.AuthenticationInterceptor.intercept(AuthenticationInterceptor.java:60)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
at com.stuhrling.interceptor.OpenSessionInViewInterceptor.intercept(OpenSessionInViewInterceptor.java:189)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
at com.stuhrling.interceptor.SessionMessageInterceptor.intercept(SessionMessageInterceptor.java:55)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:575)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:81)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.ajp.AjpAprProcessor.process(AjpAprProcessor.java:188)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2476)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2465)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [select password, salt from User where userName=:fullName and distributor_id is null]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
    at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:218)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:152)
    at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:523)
    at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:625)
    ... 31 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171)
    at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
    at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:321)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3704)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3593)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:718)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:574)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:311)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:259)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190)
    ... 37 more

Most answers were that the Entity should be queried, not the table, which I indeed did.

Code for the User class:

package com.stuhrling.domain.user;

import com.stuhrling.domain.customerservice.ProcessingLocation;
import com.stuhrling.domain.distributor.Distributor;
import com.stuhrling.domain.favorites.FavoritesItem;
import com.stuhrling.domain.offer.Customer;
import com.stuhrling.domain.offer.Offer;
import com.stuhrling.domain.permissions.Group;
import com.stuhrling.domain.permissions.Permission;
import com.stuhrling.domain.permissions.PermissionList;
import com.stuhrling.domain.permissions.PermissionsSchema;
import com.stuhrling.domain.shoppingcart.ShoppingCartItem;
import com.stuhrling.persistence.HibernateUtil;
import com.stuhrling.persistence.PersistenceException;
import com.stuhrling.util.EqualsUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.MapKey;
import javax.persistence.MapKeyColumn;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;

import org.apache.log4j.Logger;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.IndexColumn;
import org.jdom2.JDOMException;

@Entity
@Table(name = "USER", uniqueConstraints = {
    @UniqueConstraint(columnNames = {"user_name"})})
public class User {

    private static final int MAX_MRU_SIZE = 10;
    private static final Logger log = Logger.getLogger(User.class);

    public final static String ADMIN = "ADMIN";
    public final static String GENERAL = "GENERAL";
    public final static String DISTRIBUTOR = "DISTRIBUTOR";
    public final static String MANUFACTURING = "MANUFACTURING";
    public final static String PRODUCT_DEVELOPMENT = PRODUCT_DEVELOPMENT";
    public final static String PHOTOGRAPHY = "PHOTOGRAPHY";
    public static final String ACCOUNT_MANAGER = "ACCOUNT_MANAGER";
    public static final String ADMINISTRATOR = "ADMINISTRATOR";
    public static final String CUSTOMER_SERVICE = "CUSTOMER_SERVICE";
    public static final String GENERAL_ACCESS = "GENERAL_ACCESS";
    public static final String PRODUCT_AUTHOR = "PRODUCT_AUTHOR";
    public static final String SHIPPING_RECEIVING = "SHIPPING_RECEIVING";
    public static final String SUPPLIER = "SUPPLIER";

    @Column(name = "calendar_email_subscribe")
    private Boolean calendarEmailSubscribe;
    
    @Column(name = "must_reset_password")
    private Boolean mustResetPassword;

    @Transient
    private String xmlFile = "permissions.xml";

    @SuppressWarnings("unused")
    @Column(name = "salt")
    private String salt;

    @Column(name = "permission_snapshot")
    private boolean permissionCompanySnapshot = false;

    @Column(name = "permission_distributor_file_upload")
    private boolean permissionDistributorFileUpload = false;
    
    public boolean isPermissionDistributorFileUpload() {
        return permissionDistributorFileUpload;
    }

    public void setPermissionDistributorFileUlpoad(boolean permissionDistributorFileUlpoad) {
        this.permissionDistributorFileUpload = permissionDistributorFileUlpoad;
    }

    @Column(name = "full_name")
    private String fullName;

    @Column(name = "session_brand_mode")
    private String sessionBrandMode;

    @Column(name = "is_admin")
    private boolean admin = false;

    @Column(name = "exec_admin")
    private boolean execAdmin = false;
    
    @Column(name = "snap_shot_preferance", nullable = false, columnDefinition = "varchar(255) default 'false|5|0|1|0|0|5|0|1'")
    private String snapShotPreferance = "false|5|0|1|0|0|5|0|1"; /

    @OneToMany
    @MapKeyColumn(name = "brand")
    @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
    Map<String, PermissionList> brandPermissions = new HashMap<String, PermissionList>();
    
    @Column(name = "password")
    private String password;

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

    @Column(name = "user_name")
    private String userName;

    @Column
    private boolean archived = false;
    
    @ManyToOne
    @JoinColumn(name = "distributor_id", nullable = true)
    private Distributor distributor;

    @Column(name = "user_type")
    private String userType;
    
    @Column(name = "email")
    private String email;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    @OrderBy("brand asc")
    List<ShoppingCartItem> cart = new ArrayList<ShoppingCartItem>();

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    List<FavoritesItem> favorites = new ArrayList<FavoritesItem>();
    
    @OneToMany
    @MapKey(name = "id")
    @JoinTable(name = "USER_OFFERS", joinColumns = {
        @JoinColumn(name = "user_id")}, inverseJoinColumns = {
        @JoinColumn(name = "offer_id")})
    Map<Integer, Offer> userLists = new HashMap<Integer, Offer>();

    @OneToMany
    @IndexColumn(name = "idx")
    @JoinTable(name = "USER_MRU_OFFERS", joinColumns = {
        @JoinColumn(name = "user_id")}, inverseJoinColumns = {
        @JoinColumn(name = "offer_id")})
    List<Offer> mostRecentlyUsedLists = new LinkedList<Offer>();

    @ManyToMany(mappedBy = "accountManagers")
    private Set<Customer> accounts = new TreeSet<Customer>();

    @Column(name = "vendor")
    private String vendor;

    @Column(name = "brand")
    private String brand;
    
    @Column(name = "permission_edit")
    private boolean permissionToEdit;

    @Column(name = "role")
    private String role;

    @Column(name = "last_login")
    private Date lastLogin;
    
    public String getXmlFile() {
        return xmlFile;
    }

    public void setXmlFile(String xmlFile) {
        this.xmlFile = xmlFile;
    }

    public boolean isPermissionCompanySnapshot() {
        return permissionCompanySnapshot;
    }

    public void setPermissionCompanySnapshot(boolean permissionCompanySnapshot) {
        this.permissionCompanySnapshot = permissionCompanySnapshot;
    }

    public String getSnapShotPreferance() {
        return snapShotPreferance;
    }

    public void setSnapShotPreferance(String snapShotPreferance) {
        this.snapShotPreferance = snapShotPreferance;
    }

    public boolean isExecAdmin() {
        return execAdmin;
    }

    public void setExecAdmin(boolean execAdmin) {
        this.execAdmin = execAdmin;
    }

    public boolean isAdmin() {
        return admin;
    }

    public void setAdmin(boolean admin) {
        this.admin = admin;
    }

    public String getSessionBrandMode() {
        return sessionBrandMode;
    }

    public void setSessionBrandMode(String sessionBrandMode) {
        this.sessionBrandMode = sessionBrandMode;
    }

    public boolean isArchived() {
        return archived;
    }

    public void archiveUser() {
        this.archived = true;
    }

    public void unarchiveUser() {
        this.archived = false;
    }

    public String getUserType() {
        return userType;
    }

    public void setUserType(String userType) {
        this.userType = userType;
    }

    public List<FavoritesItem> getFavorites() {
        return favorites;
    }

    public void setFavorites(List<FavoritesItem> favorites) {
        this.favorites = favorites;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
        verifyAndResetBrandMode();
    }

    public List<Offer> getUserLists() {
        List<Offer> list = new ArrayList<Offer>();
        list.addAll(userLists.values());
        return list;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getId() {
        return id;
    }
    
    public String getFullName() {
        return fullName;
    }

    public String getPassword() {
        return password;
    }

    public int getUserId() {
        return id;
    }

    public String getUserName() {
        return userName;
    }
  
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

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

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public Offer getUserList(int id) {
        Offer list = userLists.get(id);
        addToMostRecentlyUsedLists(list);
        return list;
    }

    public Map<Integer, Offer> getAllUserLists() {
        return userLists;
    }
    
    public void removeList(Offer offer) {
        userLists.remove(offer.getId());
    }

    public void addToMostRecentlyUsedLists(Offer list) {
        if (list == null) {
            return;
        }

        mostRecentlyUsedLists.remove(list);
        mostRecentlyUsedLists.add(0, list);

        while (mostRecentlyUsedLists.size() > MAX_MRU_SIZE) {
            mostRecentlyUsedLists.remove(mostRecentlyUsedLists.size() - 1);
        }
    }

    public List<Offer> getRecentlyUsedLists() {
        return mostRecentlyUsedLists;
    }

    public boolean getPermissionToEdit() {
        return permissionToEdit;
    }

    public void setPermissionToEdit(boolean permissionToEdit) {
        this.permissionToEdit = permissionToEdit;
    }

    public String getRole() {
        return role;
    }

    public boolean isRole(String r) {
        return role != null && role.contains(r);
    }

    public void setRole(String role) {
        this.role = role;
    }

    public void setLastLogin(Date date) {
        this.lastLogin = date;
    }

    public Date getLastLogin() {
        return lastLogin;
    }

    public String getVendor() {
        return vendor;
    }

    public void setVendor(String vendor) {
        this.vendor = vendor;
    }

    public boolean isRestrictedVendor() {
        return (this.vendor != null && !this.vendor.equals(""));
    }

    public Set<Customer> getAccounts() {
        return accounts;
    }

    public void setAccounts(Set<Customer> accounts) {
        this.accounts = accounts;
    }

    @Override
    public String toString() {
        return this.fullName;
    }

    public Boolean getCalendarEmailSubscribe() {
        return calendarEmailSubscribe;
    }

    public void setCalendarEmailSubscribe(Boolean calendarEmailSubscribe) {
        this.calendarEmailSubscribe = calendarEmailSubscribe;
    }

    public Distributor getDistributor() {
        return distributor;
    }

    public void setDistributor(Distributor distributor) {
        this.distributor = distributor;
    }

    public boolean isDistributor() {
        return this.distributor != null;
    }

    public boolean isPermissioned(String brand, String permission) {
        boolean hasPermission = false;

        if (brandPermissions.containsKey(brand)) {
            PermissionList permissionList = brandPermissions.get(brand);
            hasPermission = permissionList.hasPermission(permission);
        }

        return hasPermission;
    }

    @Transient
    private boolean isGroupPermissioned = false;

    public boolean isGroupPermissioned(String brand, String group) throws JDOMException, IOException {
        loopThroughGroups(brand, group);

        return isGroupPermissioned;
    }

    private void loopThroughGroups(String brand, String group) throws JDOMException, IOException {
        PermissionsSchema permissions = PermissionsSchema.getInstance("permissions.xml");
        List<Group> groups = permissions.getGroups();

        for (Group groupObj : groups) {
            if (groupObj.getName().equals(group)) {
                isGroupPermissioned = true;
                loopThroughPermissions(brand, group, groupObj);
            }
        }
    }

    private void loopThroughPermissions(String brand, String group, Group groupObj) {
        for (Permission permission : groupObj.getPermissions()) {
            if (!(isPermissioned(brand, permission.getName()))) {
                isGroupPermissioned = false;
                break;
            }
        }
    }

    public List<ShoppingCartItem> getCart() {
        return cart;
    }

    public void setCart(List<ShoppingCartItem> cart) {
        this.cart = cart;
    }

    public void addPermission(String brand, String permission) {
        if (brandPermissions.containsKey(brand)) {
            addPermissionToExistingValue(brand, permission);
        } else {
            addNewKeyAndValue(brand, permission);
        }
    }

    private void addPermissionToExistingValue(String brand, String permission) {
        PermissionList permissionList = brandPermissions.get(brand);
        permissionList.addPermission(permission);
    }

    private void addNewKeyAndValue(String brand, String permission) {
        PermissionList permissionList = new PermissionList();
        permissionList.addPermission(permission);
        brandPermissions.put(brand, permissionList);
    }

    public void removePermission(String brand, String permission) {
        if (brandPermissions.containsKey(brand)) {
            PermissionList permissionList = brandPermissions.get(brand);
            permissionList.removePermission(permission);
        }
    }

    public List<String> getPermissions(String brand) {
        List<String> permissionArrayList = null;

        if (brandPermissions.get(brand) != null) {
            PermissionList permissionList = brandPermissions.get(brand);
            permissionArrayList = permissionList.getPermissions();
        }

        return permissionArrayList;
    }

    public boolean isActionPermissioned(String brand, String action) throws IOException, JDOMException {
        boolean isActionPermissioned = false;

        PermissionsSchema schema = PermissionsSchema.getInstance("permissions.xml");
        List<Permission> permissions = schema.getPermissionsHavingAction(action);

        for (Permission permission : permissions) {
            if (isPermissioned(brand, permission.getName())) {
                isActionPermissioned = true;
                break;
            }
        }

        return isActionPermissioned;
    }

    public boolean hasPermissionInGroup(String brand, String group) throws JDOMException, IOException {
        boolean hasPermissionInGroup = false;

        PermissionsSchema permissions = PermissionsSchema.getInstance(xmlFile);
        List<Group> groups = permissions.getGroups();

        for (Group groupObj : groups) {
            if (groupObj.getName().equals(group)) {
                List<Permission> permissionObjects = groupObj.getPermissions();

                for (Permission element : permissionObjects) {
                    if (isPermissioned(brand, element.getName())) {
                        hasPermissionInGroup = true;
                        break;
                    }
                }

                break;
            }
        }

        return hasPermissionInGroup;
    }

    public boolean isPermissionedForBrand(String brandToCheck) {
        if (brand == null) {
            return false;
        }

        return brand.contains(brandToCheck);
    }

    public void verifyAndResetBrandMode() {
        if (sessionBrandMode == null || !isPermissionedForBrand(sessionBrandMode)) {
            if (brand != null && !brand.isEmpty()) {
                sessionBrandMode = brand.substring(0, 1);
            }
        }
    }
  
    public void setMustResetPassword(boolean mustResetPassword) {
        this.mustResetPassword = mustResetPassword;
    }

    public Map<String, PermissionList> getBrandPermissions() {
        return brandPermissions;
    }

    public void setBrandPermissions(Map<String, PermissionList> brandPermissions) {
        this.brandPermissions = brandPermissions;
    }
    
    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "USER_PROCESSING_LOCATION", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "processing_location_id") })
    private final List<ProcessingLocation> processingLocations = new ArrayList<ProcessingLocation>();
    
    public List<ProcessingLocation> getProcessingLocations() {
        return processingLocations;
    }
    
    public void addProcessingLocation(ProcessingLocation processingLocation) {
        processingLocations.add(processingLocation);
    }

    public static void main(String[] args) throws PersistenceException {
        HibernateUtil.getCurrentSession();
    }
    
}

Entity mapping for User, other entities ommited for brevity:

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.useUnicode">true</property>
        <property name="hibernate.connection.characterEncoding">UTF-8</property>


        <!-- Connection Pool Setting -->
        <property name="hibernate.c3p0.min_size">0</property>
        <property name="hibernate.c3p0.max_size">30</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">90</property>

        <property name="hibernate.c3p0.unreturnedConnectionTimeout">2700</property>
        <property name="hibernate.c3p0.debugUnreturnedConnectionStackTraces">true</property>


        <property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
        <property name="hibernate.c3p0.preferredTestQuery">SELECT 1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">false</property>

        <!-- Drop and re-create the database schema on startup -->
<!--        <property name="hbm2ddl.auto">none</property>-->
        
        <mapping class="com.stuhrling.domain.user.User"/>
   </session-factory>
</hibernate-configuration>

Here is the query code:

private List<Object[]> getUserRecords(login){

    Session session = HibernateUtil.getCurrentSession();
    Query hql = session.createQuery("select password, salt from User where userName=:fullName");
    hql.setString("fullName", login);
    List<Object[]> results = hql.list();

    if (results.size() > 1) {
            throw new ServiceException("Database inconsistent two users with the same user name");
    }

    return results;
}

Does anyone have any ideas? I'm pretty desperate, my work has pretty much ground to a halt...

Any help would be greatly appreciated!

UPDATE: Here I've posted the HibernateUtil class as requested:

package com.stuhrling.persistence;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;


import com.stuhrling.config.AppConfig;

public class HibernateUtil {
    static Logger log = Logger.getLogger(HibernateUtil.class);

    private static SessionFactory sessionFactory;
    private static final ThreadLocal<Session> threadSession = new ThreadLocal<>();

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            final Configuration configuration = new Configuration();
            configuration.configure();

            AppConfig appConfig = AppConfig.getInstance();
            configuration.setProperty("hibernate.connection.url", appConfig.getProperty("db.url"));
            configuration.setProperty("hibernate.connection.username", appConfig.getProperty("db.username"));
            configuration.setProperty("hibernate.connection.password", appConfig.getProperty("db.password"));

            final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .configure()
                    .build();

configuration.buildSessionFactory(serviceRegistry);
            sessionFactory = new         MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
        } catch (Throwable e) {
            log.error("Unable to setup DB Connection", e);
        }
    }

    public static void closeSession() {
        try {
            final Session s = threadSession.get();
            if ((s != null) && s.isOpen()) {
                s.close();
            }
        } catch (final HibernateException ex) {
            log.error("Unable to close current session", ex);
        } finally {
            threadSession.set(null);
        }
    }

    public static Session getCurrentSession() throws PersistenceException {
        Session s = threadSession.get();
        try {
            if (s == null) {
                s = sessionFactory.openSession();
                threadSession.set(s);
            }
        }
       catch (final HibernateException ex) {
            throw new PersistenceException("Unable to get current session", ex);
        }

        return s;
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void commitTransaction() {
        threadSession.get().getTransaction().commit();
        threadSession.get().beginTransaction();
    }
}
Bishal Gautam
  • 380
  • 3
  • 16
IntelliData
  • 441
  • 6
  • 29
  • I can't see a specific mapping issue in your code, so here's some general advice. When your app starts up, check the logs carefully for anything that stands out. There tend to be a LOT of logs in general, so there may be something obvious there you're missing that explains why Hibernate can't understand something you think is simple (i.e. it might be tripping up on something else). It's happened to me this way many times before. – Atmas Apr 29 '21 at 22:06
  • @Atmas I've tried running maven in debug mode to see if there are any dependency issues in the logs, but it does not seem like there are. – IntelliData Apr 30 '21 at 13:30
  • Could you please post HibernateUtil.getCurrentSession() method or HibernateUtil class ? – Kayis Rahman May 03 '21 at 05:52
  • OK, I posted it under the UPDATE heading at the end of my post. – IntelliData May 03 '21 at 13:54
  • can you explain to me how hibernate configuration gets loaded from your hibernateutil class @IntelliData – Bishal Gautam May 03 '21 at 17:44
  • it always worked without specifying the path; I understood it to be because the hib config file was named the default name hibernate.cfg.xml and hib knew to look for it. – IntelliData May 03 '21 at 18:15
  • did you solve this @IntelliData – Bishal Gautam May 04 '21 at 07:57
  • @Bishal Gautam not really, just started from scratch with a clean project. What a pain... – IntelliData May 05 '21 at 13:58

5 Answers5

0

For some reason, the entity that you registered is not picked up. Maybe you are using a Session/SessionFactory that uses a different configuration file?

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58
0

'User' is a reserved word in mysql maybe that is the cause?

Jvo
  • 46
  • 4
0

Entities You may change two things in your code

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

all generated ID's change to:

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private int id;

HibernateUtil Apply the following change

Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
return metadata.getSessionFactoryBuilder().build();
0

With version 5 hibernate changed the naming strategies. So I think 'User' in the query does not match the 'User' class nor the 'USER' table in the database anymore.

I suggest that you change the query to use the actual table name in the database.

According to the @Table annotation, the query should look as follows:

"select password, salt from USER where userName=:fullName"

if 'USER' is the actual table name.

  • So HQL no longer recognizes class names?? – IntelliData May 05 '21 at 14:00
  • It should of course. However, I haven't completely found out what javax.persistance annotations are recognized by hql, how the classname is mapped and when the naming strategies come into play. My suspicion is that the classname is recognized, but it is translated without respecting the @Table annotation, such that the table is not found. – Otto Touzil May 05 '21 at 14:35
  • If this is true, would you consider this a bug? – IntelliData May 05 '21 at 14:42
  • I tried this, but it did not change anything. – IntelliData May 05 '21 at 16:46
  • Too bad. Can you check what the actual table name in the database is? I'm not sure if it's a bug. I had a similar problem recently, but I could solve it with a couple of tries & errors. I haven't had the time to do much research. – Otto Touzil May 06 '21 at 22:50
0

I had exactly the same problem.

Answers here Loading mapping file Hibernate 4 and Hibernate 5 ... solved the problem.

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().
configure().build();
SessionFactory sessionFactory= new Configuration().buildSessionFactory(serviceRegistry); 

Thanks

nw42
  • 1