A CallableStatement function was executed and the out parameter 1 was of type java.sql.Types=2001 however type java.sql.Types=1111 was registered - postgresql

I am trying to call a STORED PROCEDURE(with a out refcursor parameter) in postgresql through JPA2.1 like this:
public class JpaINParam {
public static void main(String[] args) throws Exception {
EntityManagerFactory emfactory = Persistence
.createEntityManagerFactory("JPA2");
EntityManager entitymanager = emfactory.createEntityManager();
entitymanager.getTransaction().begin();
StoredProcedureQuery q = entitymanager.createNamedStoredProcedureQuery("get_hibernate_dtl");
q.setParameter("modeval", "1");
q.execute();
#SuppressWarnings("unchecked")
List<Student> students = (List<Student>) q.getOutputParameterValue("resultset");
for (Student student : students) {
System.out.println(student.getFname());
}
entitymanager.getTransaction().commit();
entitymanager.close();
try {
// storedProcedure.executeUpdate();
System.out.println("444444444444");
} catch (Exception e) {
e.printStackTrace();
}
}
}
i get the following error:
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services -
2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: A CallableStatement function was executed and the out parameter 1 was of
type java.sql.Types=2001 however type java.sql.Types=1111 was
registered.
Error Code: 0
Call: {?= CALL get_hibernate_dtl(?)}
bind => [2 parameters bound]
Query: ResultSetMappingQuery(name="get_hibernate_dtl" )
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:378)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
at org.eclipse.persistence.internal.jpa.StoredProcedureQueryImpl.execute(StoredProcedureQueryImpl.java:316)
at com.javacodegeeks.examples.jpa.service.JpaINParam.main(JpaINParam.java:36)
the following is my entity class:
#NamedStoredProcedureQuery(name="get_hibernate_dtl", procedureName="get_hibernate_dtl", resultClasses={Student.class}, returnsResultSet = true, parameters={
#StoredProcedureParameter(queryParameter="resultset", name="resultset", mode=ParameterMode.REF_CURSOR,type=Class.class),
#StoredProcedureParameter(queryParameter="modeval", name="modeval", mode=ParameterMode.IN,type=String.class)
})
#Entity
public class Student {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private int sid;
private String fname;
private String lname;
private String dept;
private int year;
private String email;
public Student() {
// TODO Auto-generated constructor stub
}
public Student(int sid, String fname, String lname, String dept, int year,
String email) {
super();
this.sid = sid;
this.fname = fname;
this.lname = lname;
this.dept = dept;
this.year = year;
this.email = email;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student [sid=" + sid + ", fname=" + fname + ", lname=" + lname
+ ", dept=" + dept + ", year=" + year + ", email=" + email
+ "]";
}
}
this is my procedure in postgresql:
CREATE OR REPLACE PROCEDURE dwh.get_hibernate_dtl(resultset OUT ahis_type.refcursor, modeval IN character varying DEFAULT '1'::character varying) AS
query VARCHAR2 (6000);
v_type NUMERIC(3,0);
v_dwh_type_id VARCHAR2(100);
BEGIN
IF (modeval = 1) THEN
QUERY := ' SELECT sid,fname FROM STUDENT ';
END IF;
INSERT INTO tmp_table values ( 'get_hibernate_dtl----Modeval-->'||modeval||'query--->'||QUERY );
OPEN resultset FOR QUERY;
END

Related

How to use optional attributes in Spring Data / Webflux

I´m trying to work with joins in Spring-Webflux. I have two tables, comments and votes.
My Comment Entity has an attribute named score, which is the calculated number of votes.
The problem is this score isn´t a field inside the database, but at the moment a transient marked field in the Comment Object which is calculated by my application with bad performance.
My goal is to calculate this with a Join and not in my Application.
My Problem is that Spring doesn´t map the score field because of the transient annotation, which is needed because other Operations (patch or update) doesn´t provide this score field.
My Repository looks like this:
#Repository
public interface CommentRepository extends ReactiveCrudRepository<Comment, UUID> {
#Query("SELECT C.*, COALESCE(SUM(v.vote), 0) as score FROM comment c LEFT JOIN vote v ON c.id = v.comment_id WHERE c.room_id = $1 GROUP BY c.id")
Flux<Comment> findByRoomIdWithScore(UUID roomId);
Flux<Comment> findByRoomId(UUID roomId);
#Transactional
Flux<Void> deleteByRoomId(UUID roomId);
}
and my Comment Object is this:
#Table
public class Comment implements Persistable<UUID> {
#Id
private UUID id;
private UUID roomId;
private UUID creatorId;
private String body;
private Timestamp timestamp;
private boolean read;
private boolean favorite;
private int correct;
private boolean ack;
#Transient
private int score;
private String tag;
private String answer;
#Override
public boolean isNew() {
return id == null;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getRoomId() {
return roomId;
}
public void setRoomId(UUID roomId) {
this.roomId = roomId;
}
public UUID getCreatorId() {
return creatorId;
}
public void setCreatorId(UUID creatorId) {
this.creatorId = creatorId;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public boolean isRead() {
return read;
}
public void setRead(boolean read) {
this.read = read;
}
public boolean isFavorite() {
return favorite;
}
public void setFavorite(boolean favorite) {
this.favorite = favorite;
}
public int getCorrect() {
return correct;
}
public void setCorrect(int correct) {
this.correct = correct;
}
public boolean isAck() {
return ack;
}
public void setAck(boolean ack) {
this.ack = ack;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
#Override
public String toString() {
return "Comment{" +
"id='" + id + '\'' +
", roomId='" + roomId + '\'' +
", creatorId='" + creatorId + '\'' +
", body='" + body + '\'' +
", timestamp=" + timestamp +
", read=" + read +
", favorite=" + favorite +
", correct=" + correct +
", ack=" + ack +
", score=" + score +
", tag=" + tag +
", answer=" + answer +
'}';
}
}
I´ve already tried to make another Comment class without the transient annotation, but that doesn´t work because of the used Repository i guess: reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IllegalArgumentException: Property must not be null!
The solution was to create another Class which extends Comment with the non transient score attribute. This could be casted back into a comment and the score is set

Postgres DDL error: 'syntax error at or near "user"' [duplicate]

This question already has answers here:
Cannot create a database table named 'user' in PostgreSQL
(5 answers)
Unable to use table named "user" in postgresql hibernate
(6 answers)
Closed 3 years ago.
i am trying to setup spring boot project by using postgres database. my entities are : -
USER
#Entity
public class User implements UserDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id", nullable = false, updatable = false)
private Long id;
private String username;
private String password;
private String firstName;
private String lastName;
#Column(name="email", nullable = false, updatable = false)
private String email;
private String phone;
private boolean enabled=true;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorites = new HashSet<>();
userRoles.forEach(ur -> authorites.add(new Authority(ur.getRole().getName())));
return authorites;
}
#Override
public boolean isAccountNonExpired() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isAccountNonLocked() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isCredentialsNonExpired() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isEnabled() {
return enabled;
}
}
ROLE
#Entity
public class Role {
#Id
private int roleId;
private String name;
#OneToMany(mappedBy = "role", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private Set<UserRole> userRoles = new HashSet<>();
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
USER_ROLE
#Entity
#Table(name="user_role")
public class UserRole {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long userRoleId;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="user_id")
private User user;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="role_id")
private Role role;
public UserRole(){}
public UserRole(User user, Role role) {
this.user = user;
this.role = role;
}
public Long getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(Long userRoleId) {
this.userRoleId = userRoleId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
and my application.properties file looks like:-
server.port=5060
spring.thymeleaf.cache=false
spring.datasource.url=jdbc:postgresql://localhost:5432/pcms
spring.datasource.data-username=sagar
spring.datasource.password=sagar
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false
so whenever i run this application. user_role and role tables are created successfully on postgresql database. but user entity throws an exception.
the error says:-
2018-05-07 15:44:15.847 WARN 23619 --- [ restartedMain] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:375) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:312) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:460) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.0.1.RELEASE.jar:2.0.1.RELEASE]
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "user"
Position: 108
as you can see the error points on USER entity. but the same entity runs fine when the application is connected to mysql database. i could not quite figure out what is the real error behind it.
User is actually a reserved keyword that Spring JPA doesn't "escape" as-is. However, you can do the keyword escape like so in your entity declaration:
#Entity
#Table(name = "\"User\"")
public class User implements UserDetails { ... }
Spring is likely escaping it for you in your MySql database or taking care of it for you in some other way; not the case for your PostgreSQL DB.

The name of the variable is added to the name of the column

I have two entities - Group and UserGroup, they are connected with groupId.
"\" are because postgre is case sensitive and this way we correct this fact.
#Entity
#Table(name = "\"Group\"")
public class Group {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "\"groupId\"")
private int groupId;
#Column(name = "\"groupName\"")
private String groupName;
#OneToMany(mappedBy = "group")
List<Project> projects;
#OneToMany(mappedBy = "group")
private List<UserGroup> members;
public Group(String groupName) {
this.groupName = groupName;
}
public Group() {
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public List<UserGroup> getMembers() {
return members;
}
public void setMembers(List<UserGroup> members) {
this.members = members;
}
#Override
public String toString() {
return "Group{" +
"groupId=" + groupId +
", groupName='" + groupName + '\'' +
'}';
}
}
And UserGroup
#Entity
#Table(name = "\"UserGroup\"")
#IdClass(GroupAssociationId.class)
public class UserGroup {
#Id
#Column(name = "\"userId\"")
private int userId;
#Id
#Column(name = "\"groupId\"")
private int groupId;
#ManyToOne
#PrimaryKeyJoinColumn(name = "\"userId\"", referencedColumnName = "\"userId\"")
private User member;
#ManyToOne
#PrimaryKeyJoinColumn(name = "\"groupId\"", referencedColumnName = "\"groupId\"")
private Group group;
#ManyToOne
#JoinColumn(name = "\"accessId\"")
private Access access;
public UserGroup(Group group, User member, Access access) {
this.group = group;
this.member = member;
this.access = access;
}
public UserGroup() {
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getGroupId() {
return groupId;
}
public void setGroupId(int groupId) {
this.groupId = groupId;
}
public User getMember() {
return member;
}
public void setMember(User member) {
this.member = member;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public Access getAccess() {
return access;
}
public void setAccess(Access access) {
this.access = access;
}
#Override
public String toString() {
return "UserGroup{" +
"userId=" + userId +
", groupId=" + groupId +
", access=" + access.getAccessName() +
'}';
}
}
When I try to create a row in a table UserGroup I get a mistake:
Caused by: org.postgresql.util.PSQLException: ERROR: column "group_groupId" of relation "UserGroup" does not exist
Why? This happens on the string "em.getTransaction().commit(). It is really strange.
In the table UserGroup, a column:
"group_`groupId`"
was generated (because you are using "" to preserve case sensitive.
You can edit in postgres the name for the column (and the foreing key too):
"group_`groupId`" ---> "group_groupId"
JPA is looking for group_groupId.
I've managed to answer this question. The problem was in sequence generation. When generating in embedded database, I don't know why, the generation type sequence doesn't work. Instead I used Identity type and everything started working

Rest Client: Javax.ws.rs

i'm starting with Rest and don't have no idea how to implement it properly. I got an exercise: i must implement a Rest-Client with the RestClient-API from javax.ws.rs standard library and i tried by using the code below, but i'm getting a null pointer exception. But the resource are there and when i try directly from the browser (http://localhost:8080/sep/rest/customers/112). Now my question how can i do it properly. Some constraints, i must use XML (not JSON) for the Data-support.
Hier my client-code:
public Response createCustomer(Customer customer){
log.info("Starting: Rest Create a Customer with Name: " + Customer.class.getName());
this.customerWebTarget = this.client.target(URL);
Response response = this.customerWebTarget.request().
buildPost(Entity.entity(customer, MediaType.APPLICATION_XML)).invoke();
log.info("Ending: Rest Create a Customer with Name: " + response.getEntity().getClass().getName());
return response;
}
CustomerResource-Code:
#Path("customers")
public class CustomerResource implements IAllowedMethods<Customer> {
private static final long serialVersionUID = -6367055402693237329L;
private Logger logger = Logger.getLogger(CustomerResource.class.getName());
#Inject
private CustomerService service;
public CustomerResource() {
logger.info("create of instance " + this.getClass().getName());
}
#Override
#GET
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response get() {
List<Customer> list = service.loadAll(Customer.FINDALL, Customer.class);
if (list != null && !list.isEmpty()) {
ResponseCustomerList responseList = new ResponseCustomerList();
responseList.setList(list);
return Response.ok(responseList).build();
}
return Response.status(Status.NOT_FOUND).build();
}
.
.
.
Customer Code:
import de.ostfalia.sep.adapter.XMLIntegerAdapter;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Customer implements Serializable {
private static final long serialVersionUID = 80668466040239995L;
#XmlID
#XmlJavaTypeAdapter(XMLIntegerAdapter.class)
private Integer customerNumber;
private String customerName;
private String contactLastName;
private String contactFirstName;
private String phone;
private String addressLine1;
private String addressLine2;
private String city;
private String state;
private String postalCode;
private String country;
#XmlIDREF
private Employee salesRepEmployee;
private BigDecimal creditLimit;
private Set<Payment> payments;
private Set<Order> orders;
public Customer() {
}
public Customer(Integer customernumber) {
this.customerNumber = customernumber;
}
public Customer(Integer customerNumber, String customerName, String contactLastName, String contactFirstName,
String phone, String addressLine1, String city, String country) {
this.customerNumber = customerNumber;
this.customerName = customerName;
this.contactLastName = contactLastName;
this.contactFirstName = contactFirstName;
this.phone = phone;
this.addressLine1 = addressLine1;
this.city = city;
this.country = country;
}
public Integer getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(Integer customerNumber) {
this.customerNumber = customerNumber;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getContactLastName() {
return contactLastName;
}
public void setContactLastName(String contactLastName) {
this.contactLastName = contactLastName;
}
public String getContactFirstName() {
return contactFirstName;
}
public void setContactFirstName(String contactFirstName) {
this.contactFirstName = contactFirstName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Employee getSalesRepEmployee() {
return salesRepEmployee;
}
public void setSalesRepEmployee(Employee salesRepEmployee) {
this.salesRepEmployee = salesRepEmployee;
}
public BigDecimal getCreditLimit() {
return creditLimit;
}
public void setCreditLimit(BigDecimal creditLimit) {
this.creditLimit = creditLimit;
}
#Override
public int hashCode() {
int hash = 0;
hash += (customerNumber != null ? customerNumber.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof Customer)) {
return false;
}
Customer other = (Customer) object;
if ((this.customerNumber == null && other.customerNumber != null)
|| (this.customerNumber != null && !this.customerNumber.equals(other.customerNumber))) {
return false;
}
return true;
}
#Override
public String toString() {
return customerNumber.toString();
}
public Set<Payment> getPayments() {
return payments;
}
public void setPayments(Set<Payment> payments) {
this.payments = payments;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
}
Instead of response.getEntity(), use response.readEntity(String.class) to get the data as a String. If you want to deserialize it to a POJO, then just pass that class to the readEntity.
Also you should make sure to check the status code (response.getStatus()) to make sure it's a success status.

[Ljava.lang.Object; cannot be cast to com.yess.erp.crm.domain.Task error

I'm using Spring data jpa and i am trying to do this :
#RequestMapping(value = "/setview/{id}", method = RequestMethod.GET)
public Iterable<Task> setView(#PathVariable Integer id) {
System.out.println("setViewTrue -------------------");
Iterable<Task> tasks = taskRepository.findByUserId(id);
for (Task t : tasks) {
t.setView(true);
taskRepository.save(t);
System.out.println("task****: "+ t.isView());
}
return tasks;
}
but i got this error:
[Ljava.lang.Object; cannot be cast to com.yess.erp.crm.domain.Task
i just want to loop an iterbale of tasks and change the value of a boolean(false) to true.
this is my Task.java:
#Entity
public class Task implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "pk_sequence", sequenceName = "task_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.AUTO, generator = "pk_sequence")
private Integer id;
#NotEmpty
private String title;
#Lob
private byte[] image;
private Date created_at;
private Date start_date;
private Date end_date;
private String description;
private boolean view;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id", nullable = false)
private User user;
public Task() {
}
public Task(String title, User user) {
super();
this.title = title;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public Date getStart_date() {
return start_date;
}
public void setStart_date(Date start_date) {
this.start_date = start_date;
}
public Date getEnd_date() {
return end_date;
}
public void setEnd_date(Date end_date) {
this.end_date = end_date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getCreated_at() {
return created_at;
}
public void setCreated_at(Date created_at) {
this.created_at = created_at;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isView() {
return view;
}
public void setView(boolean view) {
this.view = view;
}
}
this is my TaskRepository.java:
public interface TaskRepository extends CrudRepository<Task, Integer> {
#Query("from Task as t inner join t.user as u where u.id = :id AND t.view = false")
Iterable<Task> findByUserId(#Param("id") Integer id);
}
this is my TaskController.java:
#RestController
#RequestMapping("/tasks")
public class TaskController {
#Autowired
private TaskRepository taskRepository;
.
.
.
#RequestMapping(value = "/setview/{id}", method = RequestMethod.GET)
public Iterable<Task> setView(#PathVariable Integer id) {
System.out.println("setViewTrue -------------------");
Iterable<Task> tasks = taskRepository.findByUserId(id);
for (Task t : tasks) {
t.setView(true);
taskRepository.save(t);
System.out.println("task****: "+ t.isView());
}
return tasks;
}
}
Your query isn't returning just a task, it is likely returning a task and user, in an Object[] array.
You might be able to alter your query to get a Task back. I'm thinking SELECT t FROM Task t...