I have used spring boot, try to retrieve all the product from the database ( MySQL ) . But list size is zero. There is no error is shown to console.
This is my controller:
#RequestMapping(value = "/showListOfProduct", method=RequestMethod.GET)
public String showList(Model model) {
List<Products> allProduct = productService.listAllProducts();
System.out.println("sizeEEEEEEEEEEEEEE"+ allProduct.size());
model.addAttribute("allProduct", allProduct);
return "showlist";
}
This is repository:
#Repository
public interface ProductRepository extends JpaRepository<Products, Long> {
}
This is service:
#Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public List<Products> listAllProducts() {
return productRepository.findAll();
}
This is my Entity:
#Entity
#Table(name="products")
public class Products {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#Column(name="productname")
private String productName;
#Column(name="numberofavailableinstock")
private long numberofavailableInStock;
#Column(name="productprice")
private String productPrice;
#Column(name="percentageofsell")
private double percentageOfSell;
// setter getter
This is my application.properties:
> spring.mvc.view.prefix: webapp/WEB-INF/jsp/ spring.mvc.view.suffix:
> .jsp server.port=7000 spring.datasource.url=
> jdbc:mysql://localhost:3306/myproduct spring.datasource.username=root
> spring.datasource.password=root
> spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.show-sql=true
My database is:
> Table: products Columns: id int(11) AI PK productname varchar(45)
> productprice varchar(45) numberofavailableinstock varchar(45)
> percentageofsell varchar
Usually when I run into this type of issue, its because my #Entity and the schema don't match up properly.
You should consider adding these two properties to your application.properties:
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
That will help you keep schema and entity matching.
Related
I have made an entity by using JPA in eclipse. The definition of the table in my MySQL is like this:
CREATE TABLE `users` (
`id` int(255) NOT NULL,
`name` varchar(255) NOT NULL,
`photo_content` text CHARACTER SET ascii DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and the equivalent entity that I generated by JPA is like this:
import java.io.Serializable;
import javax.persistence.*;
import java.util.Set;
/**
* The persistent class for the users database table.
*
*/
#Entity
#Table(name="users")
#NamedQuery(name="User.findAll", query="SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(unique=true, nullable=false)
private int id;
#Column(nullable=false, length=255)
private String name;
#Lob
#Column(name="photo_content")
private String photoContent;
//bi-directional many-to-one association to Answer
#OneToMany(mappedBy="user")
private Set<Answer> answers;
//bi-directional many-to-one association to Survey
#OneToMany(mappedBy="user")
private Set<Survey> surveys;
public User() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPhotoContent() {
return this.photoContent;
}
public void setPhotoContent(String photoContent) {
this.photoContent = photoContent;
}
public Set<Answer> getAnswers() {
return this.answers;
}
public void setAnswers(Set<Answer> answers) {
this.answers = answers;
}
public Answer addAnswer(Answer answer) {
getAnswers().add(answer);
answer.setUser(this);
return answer;
}
public Answer removeAnswer(Answer answer) {
getAnswers().remove(answer);
answer.setUser(null);
return answer;
}
public Set<Survey> getSurveys() {
return this.surveys;
}
public void setSurveys(Set<Survey> surveys) {
this.surveys = surveys;
}
public Survey addSurvey(Survey survey) {
getSurveys().add(survey);
survey.setUser(this);
return survey;
}
public Survey removeSurvey(Survey survey) {
getSurveys().remove(survey);
survey.setUser(null);
return survey;
}
}
As soon as the column photo_content has some value like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAopElEQVR42u2deXxU5b3/33NmyWQhhAQSSIIxAwIiKKCCUqgUURGdunSzYqttbW9v7/XW3uu1tW6tSzftta297e8Wf+7WrVXrWGy9Vm21WBFRQVYhkJhAyELWmcx+7h/nAFkns8+cme/79eIFLzKZ85zPeb6f86zfx3TetRciGJdwpauwqITpwAlAJVCh/zny7ylAGWAHSoACwAYUDvuqAcAP+IB+wAt0A+1AJ9AFtOr/bgMaPf3sVdqcA/IUjItFJDBMkM8B5gLzgOOB44CZeqAng8JBphDVdxaVACWuNmA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PLDroQo2AdcNe145lRZnQ/pu0gFMYCxCbc4A7oRzNaNYIeoYjh26IE/u8rqfCjc4gyIJCPJ+0HAaDDXukwH9rEauBYZLMx2XgJ+Vl3Pn/JxVF8MIMXoS4v/Dfg8YMtzObIFP/A48It8WL0nBpANTHVVHfqIq4CvAQ4RJCM0AL+pms6DtDoNesKjGIDhORRwnY82VnAx0ipINX7gOeBBaeaLAWQV5lrXpAP7uAy4AjiTJB9nlseowJvAo1XTeUbe9skjZzICZQndVVbnr4Ffm2tddboZXAwsETOIK+jfAp6rrueJoym3W0WYZCItgDSgVLtqDzbi1M1gBdJNGAs/8Brw3LQ6XOEDTjnDSQwgt7A7XBMad7EMWAWcD5yY55LsAF4EXq6bzRtGza8vBiDEhLnWZQo1O1V9NmEpsAxt3OBUcreF4Ac2AxuAN6qms+FIf/6oHoIYQD4TrnQVtrdwGtrxZ4vQUpnNwXhjCCpa/vytR4J+Sg2blDbngDxlMQAhdlM4UTeDWcBMYLr+74oMF68T2A18BOzR/711Sg07JNjFAIT0mEMdUI92bPpU/e8KoBCYBkwGCoCJ+q+Vc6xFoQIB4Ejfu1f/Px/QARwEBvRAb0Mbh28D9k2poVGC3Nj8H1wwenSbpdbLAAAAEnRFWHRFWElGOk9yaWVudGF0aW9uADGEWOzvAAAAAElFTkSuQmCC
and I try to read the Users by OData service I will see the following exception:
<error xmlns="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
<code/>
<message xml:lang="en">Missing message for key 'org.apache.olingo.odata2.api.edm.EdmSimpleTypeException.PROPERTY_VALUE_FACETS_NOT_MATCHED'!</message>
</error>
How can I solve it? I found another post here that in the answer, it has been claimed that this error is because of data type conversion but when it is long string we don't have any type casting!
It is only needed to force olingo to remove length for the attribute. By the above definition for the User entity it will end up with maxLength=255 in the metadata. So when we want to use LongText or Blob or Clob with olingo-jpa we must provide a negative size for the property, then it will assume unlimited size for the property!
#Lob
#Column(name="photo_content", length=-1)
private String photoContent;
i'm facing this issue while using Spring JPA and trying to retrieve a List of objects.
This is the class i'm trying to retrieve
#Entity
#Table(name="OBJECTSTERMIC")
public class TermicObject {
#Id
#Column(name="TERMICID")
private long termicId;
#MapsId
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="OBJECTID",columnDefinition="INTEGER")
private Object object;
#Column(name="CONTECA_RIF")
private int contecaRif;
#Column(name="CONTECA_VAL")
private int contecaVal;
#Column(name="TYPE")
private String type;
//getters and setters
The Object class has the primary key on MySQL stored as an Integer, indeed this is Object
#Entity
public class Object {
#Column(name="OBJECTID")
#Id
#JsonProperty("OBJECTID")
private int objectId;
....
So, nowhere is set a Long...
Now, i simply call in a service class
#Override
public List<TermicObject> findAll() {
return repository.findAll();
}
and got this exception
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TypeMismatchException: Provided id of the wrong type for class it.besmart.db_eipo.persistence.model.Object. Expected: class java.lang.Integer, got class java.lang.Long; nested exception is java.lang.IllegalArgumentException: org.hibernate.TypeMismatchException: Provided id of the wrong type for class it.besmart.db_eipo.persistence.model.Object. Expected: class java.lang.Integer, got class java.lang.Long
Where is set that Object Id should be Long?
Have a look at definition of your repository. Does it have right generic type? do you have Integer as second parameter? IMHO this can be root cause. See proposed correct version:
#RepositoryRestResource
public interface TermicObjectRepository extends JpaRepository<TermicObject, Integer> {
public Optional<TermicObject> findById(Integer id);
public List<TermicObject> findAll()
}
As per #Lubo's answer, in my case I was having compatibility issues between String and Long types and as my model required a Long autogenerated id I had to change the repository from
public interface ProductRepository extends JpaRepository<Product, String> {
}
to
public interface ProductRepository extends JpaRepository<Product, Long> {
}
And my controller from
#RequestMapping(path = "/products/delete/{id}", method = RequestMethod.DELETE)
public void deleteProduct(#PathVariable(name = "id") String id) {
productRepository.deleteById(id);
}
to
#RequestMapping(path = "/products/delete/{id}", method = RequestMethod.DELETE)
public void deleteProduct(#PathVariable(name = "id") Long id) {
productRepository.deleteById(id);
}
You have to define your id as a Long datatype.
#Id
#Column(name="TERMICID")
private Long termicId;
also make a change in your repository interface:
public interface ProductRepository extends JpaRepository<Product, Long> {
}
Got this because
public class MyEntity {
#Id()
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private int id; // <-------- int
...
public long getId() { return id; } // <-------- long
}
Not completely sure, but I think this mapping
#Id
#Column(name="TERMICID")
private long termicId;
#MapsId
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="OBJECTID",columnDefinition="INTEGER")
private Object object;
Makes the id of the Object match the value of termicId which is a long.
use
Long.valueOf(intValue)
to cast int to Long type because you define type Long to #Id
I am creating a simple blogging application using Spring Boot by following ( an incomplete )tutorial at: http://www.nakov.com/blog/2016/08/05/creating-a-blog-system-with-spring-mvc-thymeleaf-jpa-and-mysql/#comment-406107.
The model entity classes are as follows, Post and User:
First the code for Post:
#Entity
#Table(name="posts")
public class Post {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#Column(nullable=false, length = 300)
private String title;
#Lob #Column(nullable=false)
private String body;
#ManyToOne(optional=false, fetch=FetchType.LAZY)
private User author;
#Column(nullable = false)
private Date date = new Date();
public Post() {
}
public Post(long id, String title, String body, User author) {
this.id = id;
this.title = title;
this.body = body;
this.author = author;
}
And this is the code for User:
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Column(nullable=false, length=30, unique=true)
private String username;
#Column(length=60)
private String passwordHash;
#Column(length=100)
private String fullName;
#OneToMany(mappedBy="author")
private Set<Post> posts = new HashSet<>();
public User() {
}
public User(Long id, String username, String fullName) {
this.id = id;
this.username = username;
this.fullName = fullName;
}
Note that I have omitted package, imports, and getter/setters for convenience.
Just in case, I include my application.properties file:
spring.thymeleaf.cache = false
server.ssl.enabled=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/blog_db
spring.datasource.username=root
spring.datasource.password=somepassword
#Configure Hibernate DDL mode: create/update
spring.jpa.properties.hibernmate.hbm2ddl.auto=update
I want to create a corresponding database for my code to hook up to using mysql community server ( the workbench, to be more specific ) and since I'm completely unfamiliar with mysql I'm not having any success. ( The tut author failed to provide db script so I'm trying to recreate it ).
I'm hoping someone would be willing to help me out with the mysql database scripting.
Make sure you have the needed dependencies in your pom.xml
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
and don't forget to add this line to your application.properties.Once you have run your project replace create to update or none this will avoid the inherent drop of a table to create a new one.
spring.jpa.hibernate.ddl-auto=create
If you have any questions the following link will be a good start
https://spring.io/guides/gs/accessing-data-mysql/
I'm working on a project with Spring Data JPA. I have a table in the database as my_query.
I want to create a method which takes a string as a parameter, and then execute it as a query in the database.
Method:
executeMyQuery(queryString)
As example, when I pass
queryString= "SELECT * FROM my_query"
then it should run that query in DB level.
The repository class is as follows.
public interface MyQueryRepository extends JpaRepository<MyQuery, Long>{
public MyQuery findById(long id);
#Modifying(clearAutomatically = true)
#Transactional
#Query(value = "?1", nativeQuery = true)
public void executeMyQuery(String query);
}
However, it didn't work as I expected. It gives the following error.
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''select * from my_query;'' at line 1
Is there any other way, that I could achieve this goal?
The only part of it you can parameterise are values used in WHERE clause. Consider this sample from official doc:
public interface UserRepository extends JpaRepository<User, Long> {
#Query(value = "SELECT * FROM USERS WHERE EMAIL_ADDRESS = ?1", nativeQuery = true)
User findByEmailAddress(String emailAddress);
}
Using EntityManager you can achieve this .
Suppose your entity class is like bellow:
import javax.persistence.*;
import java.math.BigDecimal;
#Entity
#Table(name = "USER_INFO_TEST")
public class UserInfoTest {
private int id;
private String name;
private String rollNo;
public UserInfoTest() {
}
public UserInfoTest(int id, String name) {
this.id = id;
this.name = name;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", nullable = false, precision = 0)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name", nullable = true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "roll_no", nullable = true)
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
And your query is "select id, name from users where roll_no = 1001".
Here query will return an object with id and a name column. Your Response class is like below:
Your Response class is like:
public class UserObject{
int id;
String name;
String rollNo;
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNo() {
return rollNo;
}
public void setRollNo(String rollNo) {
this.rollNo = rollNo;
}
}
here UserObject constructor will get an Object Array and set data with the object.
public UserObject(Object[] columns) {
this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
this.name = (String) columns[1];
}
Your query executing function is like bellow :
public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {
String queryStr = "select id,name from users where roll_no = ?1";
try {
Query query = entityManager.createNativeQuery(queryStr);
query.setParameter(1, rollNo);
return new UserObject((Object[]) query.getSingleResult());
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
Here you have to import bellow packages:
import javax.persistence.Query;
import javax.persistence.EntityManager;
Now your main class, you have to call this function. First get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo) function. Calling procedure is given below:
Here is the Imports
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
get EntityManager from this way:
#PersistenceContext
private EntityManager entityManager;
UserObject userObject = getUserByRoll(entityManager,"1001");
Now you have data in this userObject.
Note:
query.getSingleResult() return a object array. You have to maintain the column position and data type with query column position.
select id,name from users where roll_no = 1001
query return a array and it's [0] --> id and 1 -> name.
More info visit this thread .
There is no special support for this. But what you can do is create a custom method with a String parameter and in your implementation get the EntityManager injected and execute it.
Possibly helpful links:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.custom-implementations
How to access entity manager with spring boot and spring data
Note: I would reconsider if what you are trying to do is a good idea because it bleeds implementation details of the repository into the rest of the application.
if you want to add custom query you should add #Param
#Query("from employee where name=:name")
employee findByName(#Param("name)String name);
}
this query will select unique record with match name.this will work
Thank you #ilya. Is there an alternative approach to achieve this task using Spring Data JPA? Without #Query annotation?
I just want to act on this part. yes there is a way you can go about it without using the #query annotation. what you need is to define a derived query from your interface that implements the JPA repository instance.
then from your repository instance you will be exposed to all the methods that allow CRUD operations on your database such as
interface UserRepository extends CrudRepository<User, Long> {
long deleteByLastname(String lastname);
List<User> removeByLastname(String lastname);
}
with these methods spring data will understand what you are trying to archieve and implement them accordingly.
Also put in mind that the basic CRUD operations are provided from the base class definition and you do not need to re define them. for instance this is the JPARepository class as defined by spring so extending it gives you all the methods.
public interface CrudRepository<T, ID extends Serializable>
extends Repository<T, ID> {
<S extends T> S save(S entity);
Optional<T> findById(ID primaryKey);
Iterable<T> findAll();
long count();
void delete(T entity);
boolean existsById(ID primaryKey);
}
For more current information check out the documentation at https://docs.spring.io/spring-data/jpa/docs/current/reference/html/
Based on #jelies answer, I am using the following approach
You can create another interface for your custom methods (as example MyQueryCustom) and then implement it as follows.
public class MyQueryRepositoryImpl implements MyQueryRepositoryCustom {
#PersistenceContext
private EntityManager entityManager;
public int executeQuery(String query) {
return entityManager.createNativeQuery(query).executeUpdate();
}
}
This will execute a custom query.
when trying a search on some entities in the CRUD module of Play I'm getting this exception:
play.exceptions.JavaExecutionException: org.hibernate.exception.SQLGrammarException: could not execute query
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:290)
at Invocation.HTTP Request(Play!)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1235)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1168)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:250)
at play.db.jpa.JPAPlugin$JPAModelLoader.fetch(JPAPlugin.java:431)
at controllers.CRUD$ObjectType.findPage(CRUD.java:253)
at controllers.CRUD.list(CRUD.java:36)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:413)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:408)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:182)
... 1 more
Caused by: org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.loader.Loader.doList(Loader.java:2452)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2192)
at org.hibernate.loader.Loader.list(Loader.java:2187)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:452)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1258)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:241)
... 7 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'CHARSET' in 'where clause'
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.Util.getInstance(Util.java:384)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2275)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1869)
at org.hibernate.loader.Loader.doQuery(Loader.java:718)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:270)
at org.hibernate.loader.Loader.doList(Loader.java:2449)
... 15 more
The odd thing is that search works for some entities and not for others. For example, for the following entity adding any string in the search box works:
#Entity
public class Act extends Model {
#Transient
private static final int PAGE_SIZE = Integer.parseInt(Play.configuration.getProperty("pagination.size","10"));
#Required(message = "act.name.required")
public String name;
#Required(message = "act.description.required")
#Lob
#MaxSize(value=500, message="act.description.maxsize")
public String description;
public Blob image;
public boolean showInClosedMode;
#Temporal(TemporalType.TIMESTAMP)
public Date updated;
#Required(message = "act.theatre.required")
#ManyToOne
public Theatre theatre;
public boolean disabled;
#OneToMany(mappedBy="act")
public List<Offer> offers;
#ManyToMany(cascade=CascadeType.PERSIST)
public Set<Tag> tags;
#Transient
public String tagListSupport;
[... some methods ...]
}
But not for this one:
#Entity
public class User extends Model {
#Required(message = "user.name.required")
public String name;
#Email(message = "user.email.invalid")
public String email;
public String prefLang;
public Long prefCity;
public int credits;
public Date lastLogin;
#NoBinding("profile")
public boolean disabled;
#NoBinding("profile")
public boolean admin;
#NoBinding("profile")
public boolean anonymous;
#OneToMany(mappedBy = "owner")
public List<Ticket> tickets;
#ManyToMany
public List<Theatre> theatres;
public String googleId;
public String yahooId;
public String facebookId;
public String twitterId;
public String twitter_token;
public String twitter_secret;
public String username;
public String password;
#OneToMany(mappedBy = "user")
public List<Event> history;
[...Methods...]
}
Any idea why this happens?
My guess is the database you are using does not like you having a table named "user" which is what you get when you don't provide a specific name for your table. I know that Postgres does not allow for a "user" table because "user" is a keyword. I'm not sure for MySQL. Try adding the javax.persistence.Table annotation after your #Entity annotation in the User class:
#Entity
#Table(name = "my_user")
public class User extends Model {
...
}
where you give it a whatever name you want that is not "user". Alternatively (but not tested) you may be able wrap the "user" name in quotes:
#Entity
#Table(name = "\"user\"")
public class User extends Model {
...
}
Be careful with column names.
2012-08-08T12:58:29+00:00 app[web.1]: 12:58:29,513 ERROR ~ Unsuccessful: create table users (id int8 not null, email varchar(255), enabled bool not null, name varchar(255), user varchar(255), primary key (id))
2012-08-08T12:58:29+00:00 app[web.1]: 12:58:29,514 ERROR ~ ERROR: syntax error at or near "user"
That was my case, changing column "user" to "userId" solved my issue