I'am using Hibernate framework 3.6.10.Final and MySql. I'am getting
Exception in thread "main" org.hibernate.MappingException: Cannot use identity column key generation with mapping for: org.koushik.javabrains.dto.Vehicle
when am including #Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) in vehicle class. It's working fine with out this annotation.
Vehicle.java is my base class:
#Entity
#Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Vehicle
{
#Id
#GeneratedValue
private int vehicleId;
private String vehicleName;
public int getVehicleId() {
return vehicleId;
}
public void setVehicleId(int vehicleId) {
this.vehicleId = vehicleId;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
}
TwoWheeler.java:
#Entity
public class TwoWheeler extends Vehicle {
private String SteeringHandle;
public String getSteeringHandle() {
return SteeringHandle;
}
public void setSteeringHandle(String steeringHandle) {
SteeringHandle = steeringHandle;
}
}
FourWheeler.java:
#Entity
public class FourWheeler extends Vehicle {
private String SteeringWheel;
public String getSteeringWheel() {
return SteeringWheel;
}
public void setSteeringWheel(String steeringHandle) {
SteeringWheel = steeringHandle;
}
}
My main class:
public class HibernateTest {
public static void main(String[] args)
{
Vehicle vehicle = new Vehicle();
vehicle.setVehicleName("audi"+(int)(Math.random() * 100) + 1);
TwoWheeler bike = new TwoWheeler();
bike.setVehicleName("bike");
bike.setSteeringHandle("Bike SteeringHandle");
FourWheeler car = new FourWheeler();
car.setVehicleName("car");
car.setSteeringWheel("Car SteeringHandle");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(vehicle);
session.save(bike);
session.save(car);
session.getTransaction().commit();
session.close();
}
}
And when am running am getting following error:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" org.hibernate.MappingException: Cannot use identity column key generation with mapping for: org.koushik.javabrains.dto.Vehicle
at org.hibernate.persister.entity.UnionSubclassEntityPersister.(UnionSubclassEntityPersister.java:90)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:90)
at org.hibernate.impl.SessionFactoryImpl.(SessionFactoryImpl.java:286)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872)
at org.koushik.hibernate.HibernateTest.main(HibernateTest.java:26)
if you use TABLE_PER_CLASS, you have to use this ID generation strategy: #GeneratedValue(strategy
= GenerationType.TABLE)
Vehicle.java
#Entity
#Table(name="vehicle")
#Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Vehicle
{
#Id
#GeneratedValue(strategy=GenerationType.TABLE)
#Column(name="vehicle_id")
private int vehicleId;
#Column(name="vehicle_name")
private String vehicleName;
public int getVehicleId() {
return vehicleId;
}
public void setVehicleId(int vehicleId) {
this.vehicleId = vehicleId;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
}
Related
I connected my bat to the database.
I mapped it to view the contents in HTML,
but typing url(/index) in the address bar, I can only see the contents of the table.
What is the problem?
public class Controller {
#Autowired
noticeService ns;
#RequestMapping(value="/index", method = RequestMethod.GET)
public ModelAndView index (HttpServletRequest request) {
ModelAndView mav = new ModelAndView();
List<noticeModel>noticeList = ns.getNotice();
mav.addObject("noticeList", noticeList);
mav.setViewName("index"); // HTML ADDRESS
return mav;
}
}
#Builder #Data
public class noticeModel {
private int notice_id;
private String notice_tilte;
private String notice_name;
private Date notice_created_date;
private Date notice_revised_date;
private String notice_text;
private String notice_pw;
}
#Service
public class noticeService {
#Autowired
public noticeMapper mapper;
public List<noticeModel> getNotice() {
return mapper.getNotice();
}
}
#Repository
#Mapper
public interface noticeMapper {
List<noticeModel> getNotice();
}
I am trying to save some books via request but I am getting errors. How do I exactly do this? This is the model
#Entity
public class Reservation {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String user;
private int period;
#OneToMany
private List<Books> books;
public static String error () {
return "Input error";
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public int getPeriod() { return period;}
public void setPeriod(int period) {this.period = period;}
public List<Books> getBooks() { return books;}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
#Entity
public class Books implements Serializable {
#Id
#GeneratedValue( strategy = GenerationType.IDENTITY )
private int id;
private String name;
}
}
Controller:
#PostMapping("/reserveBook")
public String reserveBook(#RequestBody Reservation reservation)
{
if (reservation.getPeriod() > 2)
return Book.error();
else{
reserveRepo.save(reservation);
return "success";
}
}
Tried json like this
{
"user": "Jason",
"books":[{"name": "Wonders"}, {"name": "Good classics"}],
"period": 2
}
What exact error you are getting? Can you try to make your inner class static? Like
public static class Books implements Serializable
I'm new to Spring Boot. I have a mysql database, I use a query to count row in my table. But it's not work, it still return my original table data. Can you help me check my code.
Here is my Entity:
#Entity
#Table(name = "act_id_membership", schema = "activiti", catalog = "")
#IdClass(ActIdMembershipEntityPK.class)
public class ActIdMembershipEntity {
private String userId;
private String groupId;
#Id
#Column(name = "USER_ID_")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Id
#Column(name = "GROUP_ID_")
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ActIdMembershipEntity that = (ActIdMembershipEntity) o;
return Objects.equals(userId, that.userId) &&
Objects.equals(groupId, that.groupId);
}
#Override
public int hashCode() {
return Objects.hash(userId, groupId);
}
}
Here is my query:
#Repository
public interface MemershipRepository extends JpaRepository<ActIdMembershipEntity, String> {
#Query ("select new com.example.activiti_restful.dtos.UserMembership(i.userId, count(i)) from ActIdMembershipEntity i where i.userId ='kermit'")
UserMembership countMemberships(String userId);
}
Updated code:
My service class:
#Service
public class MembershipService {
#Autowired
private MemershipRepository repository;
public long count() {
return repository.count();
}
My resource class:
#RestController
public class MembershipResource {
#Autowired
private MembershipService membershipService;
#GetMapping("/membership")
public long list() {return membershipService.count();}
}
My custom JSON Object class:
public class UserMembership {
private String userId;
private long numberOfusers;
public UserMembership(String userId, long numberOfusers) {
this.userId = userId;
this.numberOfusers = numberOfusers;
}
}
MySQL Table:
act_id_membership
According repositories documentation using CrudRepository provides a method called count() that is one of the Superinterfaces which JpaRepository is implemented.
Based CrudRepository documentation says:
long count(); Returns the number of entities.
Then you should use CrudRepository method. In addition Remove Uppercase MembershipREPOSITORY, by java code convention, you have to use by following way MembershipRepository.
#Repository
public interface MembershipRepository extends JpaRepository <ActIdMembershipEntity, String> {
}
And use it in your Service:
#Service
public class MembershipService {
#Autowired
private MembershipRepository repo;
public long count() {
return repo.count();
}
}
UPDATED
Based on your requirement:
In Controller:
#RestController
public class MembershipResource {
#Autowired
private MembershipService membershipService;
#GetMapping("/membership")
public List<Object> list() { return membershipService.countMemberships();
}
}
In Service:
#Service
public class MembershipService {
#Autowired
private MemershipRepository repository;
public List<Object> countMemberships() {
return repository.countMemberships();
}
}
In Repository:
#Repository
public interface MemershipRepository extends JpaRepository<ActIdMembershipEntity, String> {
#Query ("select i.userId, count(i) from ActIdMembershipEntity i where i.userId ='kermit'")
List<Object> countMemberships();
}
*> Actually I want it return a json format like [{ name: kermit, value:6}]. Now it just return a number 6 only. How I can do that? Thank you!
First, create a class to wrap your data:
public class UserMembership {
private String userId;
private long numberOfUsers;
public UserMembership(String userId, long numberOfUsers) {
this.userId = userId;
this.numerOfUsers = numberOfUsers;
}
}
Then
#Repository
public interface MembershipRepository extends JpaRepository <ActIdMembershipEntity, String> {
#Query ("select new *****.UserMembership(i.userId, count(i)) from ActIdMembershipEntity i where i.userId = :userId")
UserMembership countMemberships(String userId);
}
*****: your full package name
Hope it help!
I need your help with my JPA problem.
Please look at the following entities and primary complex keys.
#Embeddable
public class BookingPK implements Serializable
{
private static final long serialVersionUID = 1L;
private String carrid;
private String connid;
private String bookid;
public String getcarrid()
{
return this.carrid;
}
public void setcarrid(String carrid)
{
this.carrid = carrid;
}
public String getconnid()
{
return this.connid;
}
public void setconnid(String connid)
{
this.connid = connid;
}
public String getbookid()
{
return this.bookid;
}
public void setbookid(String bookid)
{
this.bookid = bookid;
}
public int hashCode()
{
return (int) ( this.carrid.hashCode())
+(int) ( this.connid.hashCode())
+(int) ( this.bookid.hashCode());
}
public boolean equals(Object obj)
{
if (obj == this) return true;
if (!(obj instanceof Booking)) return false;
BookingPK pk = (BookingPK) obj;
return pk.carrid.equals(this.carrid)
&& pk.connid.equals(this.connid)
&& pk.bookid.equals(this.bookid);
}
#Entity
public class Booking
{
#EmbeddedId
private BookingPK bookingPrimaryKey;
private String CANCELLED;
public BookingPK getbookingPrimaryKey()
{
return this.bookingPrimaryKey;
}
public void setbookingPrimaryKey(BookingPK key)
{
this.bookingPrimaryKey = key;
}
public String getCANCELLED()
{
return this.CANCELLED;
}
public void setCANCELLED(String CANCELLED)
{
this.CANCELLED = CANCELLED;
}
}
#Embeddable
public class FlightPK implements Serializable
{
private static final long serialVersionUID = 1L;
private String carrid;
private String connid;
public String getcarrid()
{
return this.carrid;
}
public void setcarrid(String carrid)
{
this.carrid = carrid;
}
public String getconnid()
{
return this.connid;
}
public void setconnid(String connid)
{
this.connid = connid;
}
public int hashCode()
{
return (int) ( this.carrid.hashCode())
+(int) ( this.connid.hashCode());
}
public boolean equals(Object obj)
{
if (obj == this) return true;
if (!(obj instanceof Flight)) return false;
FlightPK pk = (FlightPK) obj;
return pk.carrid.equals(this.carrid)
&& pk.connid.equals(this.connid);
}
}
#Entity
public class Flight
{
#EmbeddedId
private FlightPK flightPrimaryKey;
private Booking bookedFlight;
public Booking getbookedFlight()
{
return this.bookedFlight;
}
public void setbookedFlight(Booking flight)
{
this.bookedFlight = flight;
}
public FlightPK getflightPrimaryKey()
{
return this.flightPrimaryKey;
}
public void setPRICE(FlightPK key)
{
this.flightPrimaryKey = key;
}
}
Whei i run my application to create DB tables i get the following exception:
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
Exception [EclipseLink-48] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Multiple writable mappings exist for the field [FLIGHT.CONNID]. Only one may be defined as writable, all others must be specified read-only.
Mapping: org.eclipse.persistence.mappings.OneToOneMapping[bookedFlight]
Descriptor: RelationalDescriptor(testik.Flight --> [DatabaseTable(FLIGHT)])
Exception [EclipseLink-48] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Multiple writable mappings exist for the field [FLIGHT.CARRID]. Only one may be defined as writable, all others must be specified read-only.
Mapping: org.eclipse.persistence.mappings.OneToOneMapping[bookedFlight]
Descriptor: RelationalDescriptor(testik.Flight --> [DatabaseTable(FLIGHT)])
Runtime Exceptions:
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:517)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:188)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getMetamodel(EntityManagerFactoryDelegate.java:591)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getMetamodel(EntityManagerFactoryImpl.java:506)
at org.odata4j.producer.jpa.JPAEdmGenerator.generateEdm(JPAEdmGenerator.java:95)
at org.odata4j.producer.jpa.JPAProducer.<init>(JPAProducer.java:91)
at com.mockservice.MockService.<init>(MockService.java:34)
at com.mockservice.MockService.main(MockService.java:51)
Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
Please advise what is wrong. I have already tried every thing but without success.
Regards,
Slavik.
The error occurs because you have multiple attributes mapping the same columns.
You model seems very confused. If connection and carrier are unique, then why does booking need another id? Or how can a flight have a single unique booking?
Personally I would not recommend using EmbeddedId, but an IdClass instead, and use #Id on your relationship.
You may also be able to use insertable/updateable=false on your join columns, but your model seems odd.
See,
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#JPA_2.0
I used Eclipselink MOXy to convert my POJO(using JPA) to json. and it's work.
but i have one problem. I have pojo class MAccount contain many to one relation to class MProduct,. when I convert to json, result show that class MAccount not in class MProduct.
here my class MAccount implementation:
#XmlRootElement
#Entity
#Table(name="m_account")
public class MAccount extends BaseObject implements Serializable {
private static final long serialVersionUID = UUID.randomUUID().getMostSignificantBits();
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#XmlID
private Long id;
#Column(name="account_id")
private String accountId;
#Column(name="card_number")
private String cardNumber;
//bi-directional many-to-one association to Product
#ManyToOne
#JoinColumn(name="m_product_id")
#XmlIDREF
private MProduct mProduct;
public MCustomerAccount() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccountId() {
return this.accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public MProduct getMProduct() {
return this.mProduct;
}
public void setMProduct(MProduct mProduct) {
this.mProduct = mProduct;
}
// Imlement base object method
...
}
here my class MProduct implementation:
#XmlRootElement
#Entity
#Table(name="m_product")
public class MProduct extends BaseObject implements Serializable {
private static final long serialVersionUID = UUID.randomUUID().getMostSignificantBits();
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#XmlID
private Long id;
#Column(name="product_code")
private String productCode;
#Column(name="product_name")
private String productName;
//bi-directional many-to-one association to MAccount
#OneToMany(mappedBy="mProduct")
#XmlInverseReference(mappedBy="mProduct")
private Set<MAccount> mAccountList;
public MProduct() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductCode() {
return this.productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Set<MAccount> getMAccountList() {
return this.mAccountList;
}
public void setMAccountList(Set<MAccount> mAccountList) {
this.mAccountList = mAccountList;
}
// Imlement base object method
...
}
And generate JSON from MAccount class
{"MAccount":[
{"#type":"mAccount","id":"6","accountId":"05866039901"},
{"#type":"mAccount","id":"7","accountId":"25600036290"}]
}
there is no MProduct in there, the correct json result should be like below
{"MAccount":[
{"#type":"mAccount","id":6,"accountId":"05866039901","MProduct":{"#type":"mProduct","productCode":"T01","productName":"Book"}},
{"#type":"mAccount","id":7,"accountId":"25600036290","MProduct":{"#type":"mProduct","productCode":"T02","productName":"Pen"}}]
}
Is Anyone know how to solve this problem
Thank's b4
Because you are annotating the field, there is a chance that JPA has not populated that field yet due to lazy loading. If you annotate the property (get/set) instead do you still see this behaviour?
For more information on #XmlInverseReference see:
http://bdoughan.blogspot.com/2010/07/jpa-entities-to-xml-bidirectional.html