i have Grails(2.2.1) project and want to with Hibernate create simple "model" class
#Entity
#Table(name="User")
class User {
static mapping = {
datasource 'system'
}
#Id
#GeneratedValue
#Column(name="id")
private Long userId;
#Column(name="email", nullable=false)
private String email;
public User(){
}
#Transient
public Long getUserId(){
return this.userId;
}
#Transient
public String getEmail(){
return this.email;
}
}
but i getting this follow error :
Caused by MappingException: Could not determine type for: org.springframework.validation.Errors, at table: user, for columns: [org.hibernate.mapping.Column(errors)]
->> 334 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 166 | run in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . in java.lang.Thread
When i remove all hibernate annotations, app is deployed on server but table User has only two attributes (id, version).
Thank you for your help !
Move your domain class to grails-app/domain and change it to this:
class User {
String email
static mapping = {
datasource 'system'
}
static constraints = {
email nullable: false
}
}
11 lines vs. 31 lines. Groovy.
Related
package com.fhjony.ocbt
import grails.web.servlet.mvc.GrailsParameterMap
class MemberService {
def save(GrailsParameterMap params) {
Member member = new Member(params)
def response = AppUtil.saveResponse(false, member)
if (member.validate()) {
member.save(true)
if (!member.hasErrors()){
response.isSuccess = true
}
}
return response
}
def update(Member member, GrailsParameterMap params) {
member.properties = params
def response = AppUtil.saveResponse(false, member)
if (member.validate()) {
member.save(flush: true)
if (!member.hasErrors()){
response.isSuccess = true
}
}
return response
}
def getById(Serializable id) {
return Member.get(id)
}
def list(GrailsParameterMap params) {
params.max = params.max ?: GlobalConfig.itemPerPage()
List<Member> memberList = Member.createCriteria().list(params) {
if (params?.colName && params?.colValue) {
like(params.colName, "%" + params.colValue + "%")
}
if (!params.sort) {
order("id", "desc")
}
}
return [list: memberList, count: memberList.totalCount]
}
def delete(Member member) {
try {
member.delete(flush: true,failOnError:true)
} catch (Exception e) {
println(e.getMessage())
return false
}
return true
}
}
Error message:
URI /member/update Class
javax.persistence.TransactionRequiredException Message null Caused by
no transaction is in progress
Line | Method
->> 211 | invoke in org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | 188 | invoke in org.grails.core.DefaultGrailsControllerClass | 90 | handle . . . .
. in org.grails.web.mapping.mvc.UrlMappingsInfoHandlerAdapter | 1039
| doDispatch in
org.springframework.web.servlet.DispatcherServlet | 942 | doService
. . . in '' | 1005 | processRequest in
org.springframework.web.servlet.FrameworkServlet | 908 | doPost . .
. . . in '' | 882 | service in '' | 77 |
doFilterInternal in
You want your database interactions to be happening in a transactional context. One simple piece of that is you can mark your service class with #grails.gorm.transactions.Transactional.
Separate from that, and this isn't really related to your question, but passing GrailsParameterMap map around as a method argument is an unusual thing to do. What the right thing to do is depends on some factors in your app and you may want to pass values into your service rather than the whole map but if you really want the whole map in the service, one way to get there is by way of WebAttributes.
import grails.gorm.transactions.Transactional
import grails.web.api.WebAttributes
#Transactional
class MemberService implements WebAttributes {
def serviceMethod() {
// you can access params here because
// WebAttributes provides access to it
Member member = new Member(params)
// ...
}
}
I am using grails where authetication is done by Spring Security.I need to unlock User's account before login
#Transactional(readOnly=true, noRollbackFor=[IllegalArgumentException, UsernameNotFoundException])
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = User.findByUsername(username)
// Check and unlock account if 24 Hrs has been passed
userService.checkAndUnlockAccountAfter24Hrs(user.id);
if (!user) throw new NoStackUsernameNotFoundException()
def roles = user.authorities
// or if you are using role groups:
// def roles = user.authorities.collect { it.authorities }.flatten().unique()
def authorities = roles.collect {
new SimpleGrantedAuthority(it.authority)
}
return new MyUserDetails(user.username, user.password, user.enabled,
!user.accountExpired, !user.passwordExpired,
!user.accountLocked, authorities ?: NO_ROLES, user.id,
user.name)
}
Now when I do login with Remember Me check, Then It shows error:
-
| Error 2017-04-18 12:24:40,426 [http-bio-8080-exec-3] ERROR
[/].[default] - Servlet.service() for servlet [default] in context
with path [] threw exception
Message: retrieveUser returned null - a violation of the interface contract
Line | Method
->> 76 | attemptAuthentication in grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 49 | doFilter in ''
| 82 | doFilter . . . . . . in grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter
| 100 | doFilter in com.brandseye.cors.CorsFilter
| 1145 | runWorker . . . . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run . . . . . . . . . in java.lang.Thread
You have three options:
Comment out that code in boostrap in every run; except first time.
Drop database and create database for every single run
Hacky way:
Use condition(ternary operator) like this:
def adminRole = Role.findByAuthority('ROLE_ADMIN') ? : new Role(authority: 'ROLE_ADMIN').save(flush: true)
def userRole = Role.findByAuthority('ROLE_USER') ? : new Role(authority: 'ROLE_USER').save(flush: true)
def adminUser = User.findByUsername('admin') ? : new User(username: 'admin', password: 'admin', enabled: true).save(flush: true)
def user = User.findByUsername('user') ? : new User(username: 'user', password: 'user', enabled: true).save(flush: true)
if (!adminUser.authorities.contains('ROLE_ADMIN')) {
UserRole.create(adminUser, adminRole)
}
if (!user.authorities.contains('ROLE_USER')) {
UserRole.create(user, userRole)
}
I am getting the following error:
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at ../../../src/share/instrument/JPLISAgent.c line: 844
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at ../../../src/share/instrument/JPLISAgent.c line: 844
| Error 2014-08-28 09:25:11,399 [http-bio-8080-exec-5] ERROR errors.GrailsExceptionResolver - StackOverflowError occurred when processing request: [GET] /api/getProduct - parameters:
id: 14
Stacktrace follows:
Message: Executing action [getProduct] of controller [project.ApiController] caused exception: Runtime error executing action
Line | Method
->> 198 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 745 | run . . . in java.lang.Thread
my domains are as follows:
class Product {
String name
String comments
static hasMany = [components:Components]
public asJSON(){
println "product: "+this.id
def builder = new groovy.json.JsonBuilder()
def root = builder {
id this.id
name this.name
comments this.comments
components this.components.collect {it.asJSON()}
}
return builder.toString().replaceAll(/\\"/, '"').replaceAll(/\"\{/,'{').replaceAll(/\}\"/,'}')
}
}
Component:
class Components {
Product part_of
static hasMany = [alternatives:Alternatives]
public String asJSON(){
def builder = new groovy.json.JsonBuilder()
def root = builder {
id this.id
product (this.part_of)?this.part_of.asJSON():null
// alternatives (this.alternatives)?this.alternatives.collect {it.product.productAsJSON()} :null
}
return builder.toString()
}
}
When I do the following I get the exception
Product.get(1).asJSON()
I have checked that it is not recursively calling itself.
Product 1 have one Component which has a Product instance called part_of which is product with the ID 5
I am trying to pass a Json array to a Grails controller and then to a Java class. I can't figure out how to properly pass my params to the Java class though. Here is the relavent code.
AJAX POST:
$('#matrixForm').submit(function(e) {
e.preventDefault();
var matrixArray = $(this).serializeArray();
$.ajax({
type: "POST",
data: matrixArray,
url: "/turingpages/factorize/create",
success: function(data) {
//USE DATA
}
});
});
Grails Controller:
...
def create() {
MatrixFactorization m = new MatrixFactorization(params)
Gson gson = new Gson()
def jsonMatrix = gson.toJson(m.answer)
render jsonMatrix
}
...
MatrixFactorization Constructor:
public MatrixFactorization(JsonElement jsonarray) {
BlockRealMatrix R = GsonMatrix.toMatrix(jsonarray);
this.run(R);
}
My console shows my Json array as:
[{name:"00", value:"1"}, {name:"01", value:"2"}, {name:"02", value:"3"}, {name:"10", value:"4"}, {name:"11", value:"0"}, {name:"12", value:"4"}, {name:"20", value:"0"}, {name:"21", value:"4"}, {name:"22", value:"2"}]
My stack trace is:
| Error 2013-01-18 00:30:23,792 [http-bio-8080-exec-4] ERROR errors.GrailsExceptionResolver - GroovyRuntimeException occurred when processing request: [POST] /turingpages/factorize/create - parameters:
21: 4
20: 0
10: 4
22: 2
00: 1
01: 2
11: 0
02: 3
12: 4
failed to invoke constructor: public matrices.MatrixFactorization(com.google.gson.JsonElement) with arguments: [] reason: java.lang.IllegalArgumentException: wrong number of arguments. Stacktrace follows:
Message: failed to invoke constructor: public matrices.MatrixFactorization(com.google.gson.JsonElement) with arguments: [] reason: java.lang.IllegalArgumentException: wrong number of arguments
Line | Method
->> 15 | create in turingpages.rest.MFController$$ENuqtska
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 195 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run in java.lang.Thread
I am very new to using JSON. Any help is appreciated. Thanks.
1.
jQuery will pass this data as request parameters, not JSON, by default. So you should build a JSON string to pass to jQuery. I can recommend you JSON 3 library. At this case it going to be:
$.ajax({
type: "POST",
data: JSON.stringify(matrixArray),
url: "/turingpages/factorize/create",
success: function(data) {
//USE DATA
}
});
2.
On server side you could also use standard Grails JSON converter (but you could use Gson, if you prefer), see http://grails.org/Converters+Reference.
At this case you can use
def create() {
MatrixFactorization m = new MatrixFactorization(request.JSON)
render m.answer as JSON
}
I have an entity class that has an embedded object within it:
#Entity
public class Flight implements Serializable {
/// .... other attributes
#Embedded
#AttributeOverrides({
#AttributeOverride(name = "value", column =
#Column(name = "FLIGHT_TIME")),
#AttributeOverride(name = "dataState", column =
#Column(name = "FLIGHT_TIME_TYPE", length = 20))
})
private DateDataStateValue flightDate;
}
The DateDataStateValue is as follows:
#Embeddable
public class DateDataStateValue implements DataStateValue<Date>, Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "DATASTATE")
#Enumerated(value = EnumType.STRING)
private final DataState dataState;
#Column(name = "DATAVALUE")
#Temporal(TemporalType.TIMESTAMP)
private final Date value;
}
When performing a fetch of Flights from the database, using a CriteriaQuery, and creating an Order object on the time column:
Path<Flight> propertyPath = queryRoot.get("flightDate");
Order order = isAscending() ? criteriaBuilder.asc(propertyPath) : criteriaBuilder.desc(propertyPath);
The ordering is not what I want. For instance, if the flight table has the following values:
Flight 1 | ESTIMATED | 1 Jan 2012
Flight 2 | ESTIMATED | 1 Jan 2011
Flight 3 | ACTUAL | 1 Jan 2010
Flight 4 | ESTIMATED | 1 Jan 2009
The result of an ascending sort will be:
Flight 3 | ACTUAL | 1 Jan 2010
Flight 4 | ESTIMATED | 1 Jan 2009
Flight 2 | ESTIMATED | 1 Jan 2011
Flight 1 | ESTIMATED | 1 Jan 2012
It appears that the default ordering of an #Embedded column is to use the natural ordering of the elements in the order in which they are named in the class. Ie DATASTATE first, then DATAVALUE second.
What I would like to do is whenever the sort property is flightDate, the ordering is the date first, then the state, ie:
Flight 4 | ESTIMATED | 1 Jan 2009
Flight 3 | ACTUAL | 1 Jan 2010
Flight 2 | ESTIMATED | 1 Jan 2011
Flight 1 | ESTIMATED | 1 Jan 2012
Making the DateDataStateValue comparable doesn't affect it, and #orderColumn/#OrderBy don't seem to be the right thing for the job. Does anyone have any ideas?
Thanks in advance.
I didn't even know you could add an order by query on an embeddable property like this. But I wouldn't rely on it, and simply add two orders to your query:
Path<Flight> statePath = queryRoot.get("flightDate.dateState"); // or queryRoot.get("flightDate").get("dateState"): to be tested
Path<Flight> valuePath = queryRoot.get("flightDate.value");
Order[] orders;
if (isAscending()) {
orders = new Order[] {criteriaBuilder.asc(valuePath), criteriaBuilder.asc(statePath) };
}
else {
orders = new Order[] {criteriaBuilder.desc(valuePath), criteriaBuilder.desc(statePath)
}
query.orderBy(orders);
something like "flightDate.value ASC, flightDate.dataState ASC" perhaps, since all you defined was "flightDate", which implies natural ordering of that object