could not extract ResultSet in Hibernate application - java

I have problem trying authenticate user using spring security and extracting users from the db. I am using Postgres for this purpose and I am sure it is configured because I am able to manipulate entities from other tables. Here is the error I receive:
org.springframework.security.authentication.InternalAuthenticationServiceException: could not extract ResultSet
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:125)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:143)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:167)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:192)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:93)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:120)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
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:503)
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:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:449)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:202)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:100)
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:693)
at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:92)
at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1897)
at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:558)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:260)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:180)
at com.musala.ving.serviceimpl.MyUserDetailsService.buildUserAuthority(MyUserDetailsService.java:49)
at com.musala.ving.serviceimpl.MyUserDetailsService.loadUserByUsername(MyUserDetailsService.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy211.loadUserByUsername(Unknown Source)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
... 40 more
Caused by: org.postgresql.util.PSQLException: ERROR: column userrole0_.user_id does not exist
Position: 8
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1927)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:561)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:419)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:304)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
... 69 more
Here is my User class:
import java.io.Serializable;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "USERS")
public class User implements Serializable {
#Id
#Column(name = "USER_ID", unique = true, nullable = false)
private String userId;
#Column(name = "USER_NAME")
private String userName;
#Column(name = "PASSWORD")
private String password;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "DEFAULT_ROOM")
private String defaultRoom;
#Column(name = "VOICEMAIL_BOX")
private String voicemailBox;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(name = "USERS_ROOMS", joinColumns = { #JoinColumn(name = "USER_ID") }, inverseJoinColumns = { #JoinColumn(name = "ROOM_ID") })
private Set<Room> rooms = new LinkedHashSet<Room>();
#OneToMany(cascade = { CascadeType.ALL })
#JoinColumn(name = "USER_ID")
private Set<Extension> extensions = new HashSet<Extension>();
#Column(name = "LOGIN_PIN")
private String loginPin;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<UserRole> userRole = new HashSet<UserRole>(0);
#Column(name = "ENABLED")
private boolean enabled;
public User() {
super();
}
public User(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getVoicemailBox() {
return voicemailBox;
}
public void setVoicemailBox(String voicemailBox) {
this.voicemailBox = voicemailBox;
}
public Set<Room> getRooms() {
return rooms;
}
public void setRooms(Set<Room> rooms) {
this.rooms = rooms;
}
public Set<Extension> getExtensions() {
return extensions;
}
public void setExtensions(Set<Extension> extensions) {
this.extensions = extensions;
}
public String getDefaultRoom() {
return defaultRoom;
}
public void setDefaultRoom(String defaultRoom) {
this.defaultRoom = defaultRoom;
}
public String getLoginPin() {
return loginPin;
}
public void setLoginPin(String loginPin) {
this.loginPin = loginPin;
}
public Set<UserRole> getUserRole() {
return userRole;
}
public void setUserRole(Set<UserRole> userRole) {
this.userRole = userRole;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
My UserRole class:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "USER_ROLE")
public class UserRole {
private String id;
private User user;
private String role;
public UserRole() {
}
public UserRole(User user, String role) {
this.user = user;
this.role = role;
}
#Id
#Column(name = "ID", unique = true, nullable = false)
#GeneratedValue
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USER_ID", nullable = false)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getRole() {
return role;
}
#Column(name = "ROLE")
public void setRole(String role) {
this.role = role;
}
}
As a reference I used the following tutorial: http://www.mkyong.com/spring-security/spring-security-hibernate-annotation-example/
EDIT: creation of the tables:
1) user_role:
CREATE TABLE user_role
(
id character varying NOT NULL,
role character varying,
CONSTRAINT id PRIMARY KEY (id),
CONSTRAINT "user" FOREIGN KEY (id)
REFERENCES users (user_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
2) users:
CREATE TABLE users
(
id serial NOT NULL,
user_id character varying(16) NOT NULL,
user_name character varying(16),
password character varying(16),
first_name character varying(16),
last_name character varying(16),
voicemail_box character varying(16),
default_room character varying(16),
login_pin character varying(4),
enabled boolean,
CONSTRAINT users_pkey PRIMARY KEY (user_id),
CONSTRAINT users_fkey1 FOREIGN KEY (user_id)
REFERENCES user_settings (user_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
Any answers are appreciated :) sorry if it is a duplicate question. I will mark it as duplicate as soon as I have a clue what causes the error. Thank you!

You need to do the following thing
CREATE TABLE user_role
(
id character varying NOT NULL,
role character varying,
user_id character varying,
CONSTRAINT id PRIMARY KEY (id),
CONSTRAINT "user" FOREIGN KEY (user_id)
REFERENCES users (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
What you were missing was user_id column which has to be the foreign key, right now you have mapped your id field from your user_role table as both primary and foreign key.

Related

Spring Boot: Configuring AuthenticationManager with custom UserDetailsService

In my Spring Boot application, I am using JWT and a custom UserDetailsService. My AuthenticationManager is configured in a class annotated with #Configuration using the following method:
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception {
auth
.userDetailsService(userDetailsService)
.and()
.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(passwordEncoder());
}
Even though I specified a UserDetailsService, I am faced with the following problem: When my JWTLoginFilter intercepts the login request, and getAuthenticationManager().authenticate(token)
is called, I get the following exception:
org.springframework.security.authentication.InternalAuthenticationServiceException: PreparedStatementCallback; bad SQL grammar [select username,password,enabled from users where username = ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'butler-test.users' doesn't exist
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:126)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.kehrbusch.butler.apigate.jwt.JWTLoginFilter.attemptAuthentication(JWTLoginFilter.java:35)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:121)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select username,password,enabled from users where username = ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'butler-test.users' doesn't exist
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:684)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:716)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:726)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:776)
at org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl.loadUsersByUsername(JdbcDaoImpl.java:217)
at org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl.loadUserByUsername(JdbcDaoImpl.java:174)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
... 53 common frames omitted
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'butler-test.users' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:942)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1962)
at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:692)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
... 60 common frames omitted
Setting a query using usersByUsernameQuery(query) on my AuthenticationManagerBuilder solves this problem, but is this the only solution? Shouldn't the UserDetailsService provide the information needed to retrieve the UserDetails for a username?
In case it helps, here is a snippet from the JWTLoginFilter:
#Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
AccountCredentials credentials = new ObjectMapper().readValue(httpServletRequest.getInputStream(), AccountCredentials.class);
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
return getAuthenticationManager().authenticate(token);
}
This is my user entity (there are subclasses for specific users):
#Entity
#Table(name = "u_userdetails")
#Inheritance(strategy = InheritanceType.JOINED)
public class BasicUser implements UserDetails {
/**
*
*/
private static final long serialVersionUID = -109962402457721028L;
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "uuid2")
#Column(name = "id", columnDefinition = "BINARY(16)")
private UUID id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
public boolean isLocked() {
return locked;
}
#JsonDeserialize(using=LocalDateDeserializer.class)
#JsonSerialize(using=LocalDateSerializer.class)
#Column(name = "registration_date")
private LocalDate registrationDate;
#Column(name = "locked")
private boolean locked;
#Column(name = "enabled")
private boolean enabled;
#Column(name = "activation_key")
private String activationKey;
#Column(name = "email")
private String email;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable(
name = "u_user_group",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "group_id", referencedColumnName = "id")
)
private List<Group> groups;
#ElementCollection
#CollectionTable(name="u_user_role", joinColumns=#JoinColumn(name="id"))
#Column(name="role")
private List<String> roles;
protected BasicUser() {}
public BasicUser(
#JsonProperty("id") UUID id,
#JsonProperty("username") String username,
#JsonProperty("password") String password,
#JsonProperty("registrationDate") LocalDate registrationDate,
#JsonProperty("locked") boolean locked,
#JsonProperty("enabled") boolean enabled,
#JsonProperty("activationKey") String activationKey,
#JsonProperty("email") String email,
#JsonProperty("roles") List<String> roles) {
this.id = id;
this.username = username;
this.password = password;
this.registrationDate = registrationDate;
this.locked = locked;
this.enabled = enabled;
this.activationKey = activationKey;
this.email = email;
this.roles = roles;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public static List<GrantedAuthority> getAuthorities(List<String> roles) {
List<GrantedAuthority> res = new ArrayList<>();
for(String role : roles) {
res.add(new BasicGrantedAuthority(role));
}
return res;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return !locked;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return enabled;
}
public LocalDate getRegistrationDate() {
return registrationDate;
}
public UUID getId() {
return id;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getAuthorities(roles);
}
public void setLocked(boolean locked) {
this.locked = locked;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
}
Your configuration is wrong. You defined 2 authentication mechanisms, one is a user details service, and the second is a JDBC authentication.
In order to authenticate a user you only need one kind of mechanism to do that.
Your JVM "complains" about a bad SQL grammar, and if you'll examine the exception more closely you'll see that in particular JVM "complains" that he can't find the users table in your DB.
It seems that your JDBC authentication kicks in and tries to find the user credentials in the users DB table.
When you use this kind of authentication (JDBC) that is where and how Spring will try to authenticate the users, by trying to find a matching record within the users table in your DB.
You obviously mixing 2 authentications mechanisms by trying to read from:
#Table(name = "u_userdetails")
If you want to use JDBC authentication make sure to read the credentials from users table.
And not from:
#Table(name = "u_userdetails")

Hibernate 5.0.6 Configuration Exception : The application must supply JDBC connections

I'm trying to implement Simple application of Hibernate 5.0.6 in which I'm trying to get the data from the user table and just print on console
I'm facing following exception while invoking the session.beginTransaction() method of session object.
I've given all the necessary details required for JDBC Connection in hibernate.cfg.xml
Exception which is rising is as follows:
java.lang.UnsupportedOperationException: The application must supply JDBC connections
at org.hibernate.engine.jdbc.connections.internal.UserSuppliedConnectionProviderImpl.getConnection(UserSuppliedConnectionProviderImpl.java:44)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:386)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:87)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:112)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:230)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:237)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:214)
at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1512)
at com.getAWay.rest.HelloWorldService.getUserDetails(HelloWorldService.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:308)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:291)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1140)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:403)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I'm using hibernate 5.0.6 version.
Code written in hibernate.cfg.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-/Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuratoin-3.0dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hiberante.connection.url">jdbc:mysql://localhost:3306/test_hibernate</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="com.getAWay.entity.UserDetail"></mapping>
</session-factory>
</hibernate-configuration>
In above code I've provided all the JDBC Configuration properly.
But still facing the problem related to JDBC Connection
My domain Class in which I've mapped all the columns properly to each class variables accordingly
UserDetail Class as follows:
import java.util.Calendar;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.hibernate.annotations.Type;
/**
* #author Gj
*
*/
//#Entity
//#Table(name = "user_details", catalog = "test_hibernate", uniqueConstraints = { #UniqueConstraint(columnNames = "phoneNumber") })
public class UserDetail implements java.io.Serializable{
private static final long serialVersionUID = -329979543771878237L;
/**
*
*/
public UserDetail() {
// TODO Auto-generated constructor stub
}
private long userId;
private int phoneNumber;
private String firstName;
private String middleName;
private String lastName;
private String displayPhoto;
private Calendar created;
private Calendar updated;
private boolean deleted;
// private boolean isActive;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "userId", unique = true, nullable = false)
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
#Column(name = "phoneNumber", unique = true, nullable = false, length = 10)
public int getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Column(name = "firstName", unique = true, nullable = false, length = 30)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "middleName", unique = true, nullable = false, length = 30)
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
#Column(name = "lastName", unique = true, nullable = false, length = 30)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "displayPhoto", unique = true, nullable = false, length = 255)
public String getDisplayPhoto() {
return displayPhoto;
}
public void setDisplayPhoto(String displayPhoto) {
this.displayPhoto = displayPhoto;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created", nullable = false)
public Calendar getCreated() {
return created;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated", nullable = false)
public Calendar getUpdated() {
return updated;
}
#Type(type = "numeric_boolean")
#Column(name = "deleted", nullable = false)
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
#PrePersist
protected void onCreate() {
updated = created = Calendar.getInstance();
}
#PreUpdate
protected void onUpdate() {
updated = Calendar.getInstance();
}
public String toString()
{
return "[User Id :"+userId+" Ph No :"+phoneNumber+" Name :"+firstName+" "+middleName+" "+lastName
+" Is Deleted :"+deleted+"]";
}
}
What is missing here? I'm not able to understand. Please help me for this.
Thanks in advance.
There is a typo in your config:
<property name="hiberante.connection.url">jdbc:mysql://lo...
Should read:
<property name="hibernate.connection.url">jdbc:mysql://lo
hiberante vs hibernate. Since that parameter was the connection url Hibernate did not receive any instruction on how to connect to your db, hence the errormessage.
Try to change this typo hiberante in this line:
<property name="hiberante.connection.url">...
With hibernate like this:
<property name="hibernate.connection.url">...

Getting null identifier error in entity class during update query

Entity class:
package com.rapid.admin.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* LoginHistory entity. #author MyEclipse Persistence Tools
*/
#Entity
#Table(name = "login_history", catalog = "project")
public class LoginHistory implements java.io.Serializable {
// Fields
private Integer id;
private String username;
private Timestamp loginTime;
private Timestamp logoutTime;
private Boolean status;
private String timeId;
// Constructors
/** default constructor */
public LoginHistory() {
}
/** full constructor */
public LoginHistory(String username, Timestamp loginTime,
Timestamp logoutTime, Boolean status, String timeId) {
this.username = username;
this.loginTime = loginTime;
this.logoutTime = logoutTime;
this.status = status;
this.timeId = timeId;
}
// Property accessors
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "username", length = 45)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "login_time", length = 19)
public Timestamp getLoginTime() {
return this.loginTime;
}
public void setLoginTime(Timestamp loginTime) {
this.loginTime = loginTime;
}
#Column(name = "logout_time", length = 19, updatable= true)
public Timestamp getLogoutTime() {
return this.logoutTime;
}
public void setLogoutTime(Timestamp logoutTime) {
this.logoutTime = logoutTime;
}
#Column(name = "status")
public Boolean getStatus() {
return this.status;
}
public void setStatus(Boolean status) {
this.status = status;
}
#Column(name = "time_id", length = 45)
public String getTimeId() {
return this.timeId;
}
public void setTimeId(String timeId) {
this.timeId = timeId;
}
Hibernate query :
sessionFactory.getCurrentSession().beginTransaction();
Criteria criteria =
sessionFactory.getCurrentSession().createCriteria(LoginHistory.class);
criteria.add(Restrictions.eq("id",id));
LoginHistory loginHistory = new LoginHistory();
loginHistory.setLogoutTime(AdminUtil.getTimeStamp());
sessionFactory.getCurrentSession().update(loginHistory);
Error on console:
org.hibernate.TransientObjectException: The given object has a null identifier: com.rapid.admin.entity.LoginHistory
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.getUpdateId(DefaultSaveOrUpdateEventListener.java:272)
at org.hibernate.event.def.DefaultUpdateEventListener.getUpdateId(DefaultUpdateEventListener.java:69)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:240)
at org.hibernate.event.def.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireUpdate(SessionImpl.java:592)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:580)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:572)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:342)
at $Proxy21.update(Unknown Source)
at com.rapid.admin.daoimpl.LoginDaoImpl.updateLogoutTime(LoginDaoImpl.java:117)
at com.rapid.admin.serviceimpl.LoginServiceImpl.updateLogoutTime(LoginServiceImpl.java:53)
at com.rapid.admin.controller.LoginController.logout(LoginController.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
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:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
org.hibernate.TransientObjectException: The given object has a null identifier: com.rapid.admin.entity.LoginHistory
I guess you should write like this : (by considering you want to update LoginHistory which is already in DB having id that you are passing)
hibernate query :
sessionFactory.getCurrentSession().beginTransaction();
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(LoginHistory.class);
criteria.add(Restrictions.eq("id",id));
LoginHistory loginHistory = (LoginHistory)criteria.uniqueResult();
loginHistory.setLogoutTime(AdminUtil.getTimeStamp());
sessionFactory.getCurrentSession().update(loginHistory);

java jpa ManyToOne cascade remove not working as expected

I have two tables and on one of which I want to perform cascade on delete operation. I have tried using annotations both on the variable and on the getter method as well, but the variable one gives me this error:
An error occured
org.hibernate.exception.DataException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:102)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at no.nhst.user.dao.hibernate.IPUserDAOImpl.saveOrUpdate(IPUserDAOImpl.java:78)
at no.nhst.user.service.IPUserServiceImpl.saveOrUpdateIPUser(IPUserServiceImpl.java:103)
at no.nhst.user.web.admin.IPCustomerController.submitIpUsers(IPCustomerController.java:97)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.sql.BatchUpdateException: Data truncation: Out of range value adjusted for column 'user_account' at row 1
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2028)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1451)
at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297)
at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 79 more
Caused by: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Out of range value adjusted for column 'user_account' at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3607)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2427)
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1980)
... 84 more
Which is out of question because the column its referring to has BIGINT(10) size.
And, when I try using many to one annotation on getter method its not doing anything at all.
Here is my parent entity class:
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import no.nhst.user.model.resolver.AuthoritiesResolver;
import no.nhst.user.model.resolver.DefaultAuthoritiesResolver;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
#Entity
#Table(name = "ac_useraccount", uniqueConstraints = { #UniqueConstraint(columnNames = { "domain", "username" }) })
public class UserAccount extends BaseEntity implements UserDetails {
private static final long serialVersionUID = 1L;
private static final Log logger = LogFactory.getLog(UserAccount.class);
private String domain;
private String username;
private String password;
private String email;
private UserProfile userProfile;
private Date created;
private Date lastlogin;
private Date expires;
private Date credentialsExpires;
private boolean enabled = false;
private boolean locked = false;
private Set<Role> roles;
private Set<Group> groups;
private Set<UserApplication> applications;
private Set<Tag> tags = new HashSet<Tag>(); // optional "tags" to categorize a user in some way (not required)
private int maxSessions;
private AuthoritiesResolver authoritiesResolver;
UserAccount() {
this.applications = new HashSet<UserApplication>();
this.authoritiesResolver = new DefaultAuthoritiesResolver();
}
UserAccount(String domain, String username) {
this(domain, username, null, null, false);
}
UserAccount(String domain, String username, String password, String email, boolean enabled) {
this();
this.domain = domain;
this.username = username;
this.password = password;
this.email = email;
this.enabled = enabled;
}
public void setDomain(String domain) {
this.domain = domain;
}
public void setUserProfile(UserProfile userProfile) {
this.userProfile = userProfile;
if (null != userProfile)
userProfile.setUserAccount(this);
}
/** See http://docs.jboss.org/hibernate/core/3.5/reference/en-US/html/objectstate.html#objectstate-transitive */
// TODO: See AVIS-589 (update: that Jira issue is resolved)
#OneToOne(orphanRemoval=false,fetch = FetchType.LAZY)
#Cascade({CascadeType.ALL})
public UserProfile getUserProfile() {
return userProfile;
}
// TODO: AVIS-607, set to FetchType.EAGER temporarily
#OneToMany(mappedBy="userAccount", fetch=FetchType.LAZY)
#Cascade({CascadeType.ALL})
public Set<UserApplication> getApplications() {
return this.applications;
}
public void setApplications(Set<UserApplication> applications) {
this.applications = applications;
}
#OneToMany(mappedBy = "userAccount")
#Cascade({CascadeType.ALL})
public Set<Tag> getTags() {
return tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
#Basic
public int getMaxSessions() {
return maxSessions;
}
public void setMaxSessions(int maxSessions) {
this.maxSessions = maxSessions;
}
#Temporal(TemporalType.TIMESTAMP)
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
#Temporal(TemporalType.TIMESTAMP)
public Date getLastlogin() {
return lastlogin;
}
public void setLastlogin(Date lastlogin) {
this.lastlogin = lastlogin;
}
// Transient (dependent on other fields) Spring Security UserDetails methods
#Transient
public Set<GrantedAuthority> getAuthorities() {
return authoritiesResolver.resolveAuthorities(this);
}
#Transient
public boolean isAccountNonExpired() {
boolean accountNonExpired = true;
if(this.expires != null) {
Date now = new Date();
if(now.after(expires)) {
accountNonExpired = false;
}
}
return accountNonExpired;
}
#Transient
public boolean isCredentialsNonExpired() {
boolean credentialsNonExpired = true;
if(this.credentialsExpires != null) {
Date now = new Date();
if(now.after(credentialsExpires)) {
credentialsNonExpired = false;
}
}
return credentialsNonExpired;
}
#Transient
public boolean isAccountNonLocked() {
return !this.locked;
}
public void setAccountNonLocked(boolean accountNonLocked) {
this.locked = !accountNonLocked;
}
public void setAuthoritiesResolver(AuthoritiesResolver authoritiesResolver) {
this.authoritiesResolver = authoritiesResolver;
}
#Transient
public AuthoritiesResolver getAuthoritiesResolver() {
return authoritiesResolver;
}
#Transient
public void addRole(Role role) {
this.getRoles().add(role);
role.getUserAccounts().add(this);
}
#Transient
public void removeRole(Role role) {
this.getRoles().remove(role);
role.getUserAccounts().remove(this);
}
#Transient
public void addGroup(Group group) {
this.getGroups().add(group);
group.getUserAccounts().add(this);
}
}
And here is my child class where I have used many to one annotation:
import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name="ac_ua_ip")
public class IPUser extends BaseEntity{
private static final long serialVersionUID = 1L;
private String ip;
private String comment;
private UserAccount userAccount;
public IPUser(){
}
public IPUser (String ip, String comment, UserAccount userAccount){
this.ip = ip;
this.comment = comment;
this.setUserAccount(userAccount);
}
#Column (nullable = false)
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
#Column
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
#ManyToOne(cascade = CascadeType.REMOVE)
public UserAccount getUserAccount() {
return userAccount;
}
public void setUserAccount(UserAccount userAccount) {
this.userAccount = userAccount;
}
}
And, I have removed lot of methods from parent class here just to have a clarity.
Any suggestions as to what I am doing wrong?
You will have to manage that problem manually, as it really does NOT make sense to cascade the remove operations from a ManyToOne relationship (otherwise your DB will not be consistent, as there could remain some IPUser entities without UserAccount).
See this answer for an excerpt from the JPA specification + a similar problem.
Alright, here's how I made it work.
I hope it goes all ok with the etiquette of answering self-asked-questions.
I added a reference to IPUser class in UserAccount class and it worked smoothly now. Here is the snippet I added:
private List<IPUser> ipUserList;
#OneToMany(mappedBy = "userAccount", fetch = FetchType.LAZY)
#Cascade({CascadeType.DELETE})
public List<IPUser> getIpUserList() {
return ipUserList;
}
public void setIpUserList(List<IPUser> ipUserList) {
this.ipUserList = ipUserList;
}
Please feel free to update my answer or ask any question regarding this.

Many to many extra column - MySQLIntegrityConstraintViolationException: Column 'BAND_ID' cannot be null

I'm trying to save a Entity with relationship many to many with extra column but I've received an error
Band.java
package it.entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* The persistent class for the band database table.
*
*/
#Entity
#Table(name="BAND")
#NamedQuery(name="Band.findAll", query="SELECT b FROM Band b")
public class Band implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
private int id;
#Column(name="DESCRIZIONE")
private String descrizione;
#Column(name="NOME")
private String nome;
//bi-directional many-to-one association to Audio
#ManyToOne
#JoinColumn(name="AUDIO_ID")
private Audio audio;
//bi-directional many-to-one association to Video
#ManyToOne
#JoinColumn(name="VIDEO_ID")
private Video video;
//bi-directional many-to-one association to Citta
#ManyToOne
#JoinColumn(name="CITTA_ID")
private Citta citta;
#OneToMany(mappedBy="pk.band", fetch = FetchType.LAZY, cascade={CascadeType.ALL})
private List<BandHasMusicista> bandHasMusicista = new ArrayList<BandHasMusicista>();
public Band() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getDescrizione() {
return this.descrizione;
}
public void setDescrizione(String descrizione) {
this.descrizione = descrizione;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Audio getAudio() {
return this.audio;
}
public void setAudio(Audio audio) {
this.audio = audio;
}
public Video getVideo() {
return this.video;
}
public void setVideo(Video video) {
this.video = video;
}
public Citta getCitta() {
return this.citta;
}
public void setCitta(Citta citta) {
this.citta = citta;
}
// #OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.band")
public List<BandHasMusicista> getBandHasMusicista() {
return bandHasMusicista;
}
public void setBandHasMusicista(List<BandHasMusicista> bandHasMusicista) {
this.bandHasMusicista = bandHasMusicista;
}
}
BandHasMusicista.java
package it.entities;
import java.io.Serializable;
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* The persistent class for the band_has_musicista database table.
*
*/
#Entity
#Table(name="BAND_HAS_MUSICISTA")
#AssociationOverrides({
#AssociationOverride(name = "pk.musicista", joinColumns = #JoinColumn(name = "MUSICISTA_ID")),
#AssociationOverride(name = "pk.band", joinColumns = #JoinColumn(name = "BAND_ID"))})
#NamedQuery(name="BandHasMusicista.findAll", query="SELECT b FROM BandHasMusicista b")
public class BandHasMusicista implements Serializable {
private static final long serialVersionUID = 1L;
private BandHasMusicistaPK pk = new BandHasMusicistaPK();
private Band band;
private Musicista musicista;
private boolean bandAccept;
private boolean musicistaAccept;
public BandHasMusicista() {
}
#EmbeddedId
public BandHasMusicistaPK getPk() {
return pk;
}
public void setPk(BandHasMusicistaPK pk) {
this.pk = pk;
}
#Column(name="BAND_ACCEPT", nullable=false)
public boolean getBandAccept() {
return this.bandAccept;
}
public void setBandAccept(boolean bandAccept) {
this.bandAccept = bandAccept;
}
#Column(name="MUSICISTA_ACCEPT", nullable=false)
public boolean getMusicistaAccept() {
return this.musicistaAccept;
}
public void setMusicistaAccept(boolean musicistaAccept) {
this.musicistaAccept = musicistaAccept;
}
#Transient
// #JoinColumn(name="BAND_ID")
public Band getBand() {
return this.band;
}
public void setBand(Band band) {
this.band = band;
}
#Transient
// #JoinColumn(name="MUSICISTA_ID")
public Musicista getMusicista() {
return this.musicista;
}
public void setMusicista(Musicista musicista) {
this.musicista = musicista;
}
}
BandHasMusicistaPK.java
package it.entities;
import java.io.Serializable;
import javax.persistence.*;
/**
* The primary key class for the band_has_musicista database table.
*
*/
#Embeddable
public class BandHasMusicistaPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
private Band band;
private Musicista musicista;
public BandHasMusicistaPK() {
}
#ManyToOne
// #JoinColumn(name="BAND_ID")
public Band getBand() {
return this.band;
}
public void setBand(Band band) {
this.band = band;
}
#ManyToOne
// #JoinColumn(name="MUSICISTA_ID")
public Musicista getMusicista() {
return this.musicista;
}
public void setMusicista(Musicista musicista) {
this.musicista = musicista;
}
}
Musicista.java
package it.entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
/**
* The persistent class for the MUSICISTA database table.
*
*/
#Entity
#Table(name="MUSICISTA")
#NamedQuery(name="Musicista.findAll", query="SELECT m FROM Musicista m")
public class Musicista implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(generator="SharedPrimaryKeyGenerator")
#GenericGenerator(name="SharedPrimaryKeyGenerator", strategy="foreign", parameters = #Parameter(name="property", value="account"))
#Column(name = "ID", unique = true, nullable = false)
private int id;
#Column(name="COGNOME", nullable=false, length=155)
private String cognome;
#Temporal(TemporalType.DATE)
#Column(name="DATA_NASCITA")
private Date dataNascita;
#Column(name="NOME", nullable=false, length=155)
private String nome;
//bi-directional one-to-one association to Account
#OneToOne
#PrimaryKeyJoinColumn
private Account account;
#OneToMany(mappedBy="pk.musicista", fetch = FetchType.LAZY, cascade={CascadeType.ALL})
private List<BandHasMusicista> bandHasMusicista = new ArrayList<BandHasMusicista>();
public Musicista() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getCognome() {
return this.cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public Date getDataNascita() {
return this.dataNascita;
}
public void setDataNascita(Date dataNascita) {
this.dataNascita = dataNascita;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Account getAccount() {
return this.account;
}
public void setAccount(Account account) {
this.account = account;
}
// #OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.musicista")
public List<BandHasMusicista> getBandHasMusicista() {
return bandHasMusicista;
}
public void setBandHasMusicista(List<BandHasMusicista> bandHasMusicista) {
this.bandHasMusicista = bandHasMusicista;
}
}
BandLogic.java
package it.logic;
import it.entities.Band;
import it.entities.BandHasMusicista;
import it.entities.Citta;
import it.entities.Musicista;
import it.interfaces.ServiceBean;
import it.invo.AddBandInVO;
import javax.persistence.EntityManager;
public class BandLogic {
EntityManager em = null;
/**
* Default constructor.
*/
public BandLogic() {
em = ServiceBean.getEm();
}
public boolean addBand(AddBandInVO inVO) {
System.out.println("IN - addBand() INPUT = " + inVO);
Musicista musicista = em.find(Musicista.class, inVO.getAccountId());
Citta citta = em.find(Citta.class, inVO.getCitta());
if(musicista != null){
Band band = new Band();
band.setNome(inVO.getNome());
band.setDescrizione(inVO.getDescrizione());
band.setCitta(citta);
BandHasMusicista bandHasMusicista = new BandHasMusicista();
bandHasMusicista.setBand(band);
bandHasMusicista.setMusicista(musicista);
bandHasMusicista.setBandAccept(true);
bandHasMusicista.setMusicistaAccept(true);
band.getBandHasMusicista().add(bandHasMusicista);
em.persist(band);
em.flush();
em.clear();
}else{
System.out.println("Account is not Musicista");
return false;
}
System.out.println("OUT - addBand()");
return true;
}
}
The stack trace:
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:614)
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:307)
at it.logic.BandLogic.addBand(BandLogic.java:46)
at it.interfaces.ServiceBean.addBand(ServiceBean.java:184)
at it.test.BandTest.testAddBand(BandTest.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:304)
... 22 more
Caused by: java.sql.BatchUpdateException: Column 'BAND_ID' cannot be null
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2054)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1467)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 28 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'BAND_ID' cannot be null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4187)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4119)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2006)
... 31 more
In this code:
if(musicista != null){
Band band = new Band();
band.setNome(inVO.getNome());
band.setDescrizione(inVO.getDescrizione());
band.setCitta(citta);
BandHasMusicista bandHasMusicista = new BandHasMusicista();
bandHasMusicista.setBand(band);
bandHasMusicista.setMusicista(musicista);
bandHasMusicista.setBandAccept(true);
bandHasMusicista.setMusicistaAccept(true);
band.getBandHasMusicista().add(bandHasMusicista);
em.persist(band);
em.flush();
em.clear();
}
you are creating a new Band and then you are trying to add a Musicista to band. The problem is that at the moment you do em.persist(band) the generated SQL is trying to save the Musicista before saving the Band, therefore BAND_ID which is generated automatically is still null. Save the Band as
if(musicista != null){
Band band = new Band();
band.setNome(inVO.getNome());
band.setDescrizione(inVO.getDescrizione());
band.setCitta(citta);
band = em.persist(band);
BandHasMusicista bandHasMusicista = new BandHasMusicista();
bandHasMusicista.setBand(band);
bandHasMusicista.setMusicista(musicista);
bandHasMusicista.setBandAccept(true);
bandHasMusicista.setMusicistaAccept(true);
band.getBandHasMusicista().add(bandHasMusicista);
em.persist(band);
em.flush();
em.clear();
}
should work (I think you can also do simply em.persist(band); also in the first save, but I am not sure).

Categories

Resources