Query execution problem using Spring and HIbernate together with FLEX - apache-flex

So I'm going to be using Flex 4 with Spring and Hibernate.
Everything is configured and working. I know this as I can do simple queries, like listing all values in a table.
Problem is when I try to perform a 'select' query, then I get all the values, as I was getting before, and not the specific attributes through Select query.
I'm a beginner, so kindly overlook my lack of more technically sound words..but I don use them as I don wanna mis-quote.
Following is some code which will make You understand things better:
This is class used to store data coming from the MySQL database--
package flex;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="intrial1")
public class intrial1 implements Serializable {
#Id #GeneratedValue
#Column( name = "id")
private int id;
#Column( name = "name")
private String name;
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;
}
}
This is the class where the sessionFactory does things(too many import statements, just to try to make things work-ignore)--
package flex;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import org.hibernate.SessionFactory;
import org.hibernate.annotations.NamedNativeQueries;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.flex.remoting.RemotingInclude;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Transactional;
#Repository
#RemotingDestination
public class SpringBean_Service {
private SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory factory) {
sessionFactory = factory;
}
#SuppressWarnings("unchecked")
#RemotingInclude
#Transactional
public List<intrial1> getList() {
return sessionFactory.getCurrentSession().createQuery("from intrial1 ").list();
}
#SuppressWarnings("unchecked")
#RemotingInclude
#Transactional
public List<intrial1> getListAgain() {
org.hibernate.Query q = sessionFactory.getCurrentSession().createQuery("select id from intrial1 where name='chirayu'");
List l = q.list();
return l;
}
#RemotingInclude
#Transactional
public void createFriend(String name, int id) {
intrial1 f = new intrial1();
f.setName(name);
f.setId(id);
sessionFactory.getCurrentSession().save(f);
}
}
In above class, getList() works
perfect, lists all the values. The
createFriend is used to enter values
of id+name, and works smoothly. The
problem is with getListAgain()
function, it gives me a result,
imagine 2 columns, having heading as
'id' and 'name', but listing id values
in both the columns (No names), As You
can understand, I am looking for
result of getListAgain() function as -
"1 column having header as 'id', and
listing id wherever the name
='chirayu'".
Kindly help, as I will need to clear this and move ahead with development.
Thank You.
Regards,
Chirayu
UPDATE NOTE: Would like to say one thing here, if only I make a class as below, which is identical to intrial1 class, but has no return statement for name, i.e., no getName() defined, I get my correct result for the query -
'select id from intrial1 where
name='chirayu''
package flex;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class intrial2 {
#Id #GeneratedValue
#Column( name = "id")
private int id;
#Column( name = "name")
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
Is this strange or meant to be like this. Still looking for answers.

The query
select id from intrial1 where name='chirayu'
doesn't return intrial1 entity, so you should change return type to List or simply change your query to:
from intrial1 where name='chirayu'

Related

Java Code to invoke PATCH method from JUnit

I have a simple MyLibraryApplication which is having code to invoke POST(TransactionControllerImpl.issueBookToMember) and PATCH(TransactionControllerImpl.returnBookTransaction) methods. I have referred some links on net and tried my best to write code to invoke PATCH method. The code can be found in TransactionControllerTest(testBookReturnUsingRestTemplate and testBookReturnUsingMockMvc methods). The code for invoking POST is working fine but the code for invoking PATCH is not working. Control never reaches returnBookTransaction inside TransactionControllerImpl.
Error: Invalid PATCH method.
I am looking for code snippet for TransactionControllerTest.testBookReturnUsingRestTemplate and testBookReturnUsingMockMvc methods. Can someone help me in getting this code into proper shape?
package com.mycompany.techtrial;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import com.mycompany.techtrial.Transaction;
public interface TransactionController {
public ResponseEntity<Transaction> issueBookToMember(#RequestBody Map<String, String> params);
public ResponseEntity<Transaction> returnBookTransaction(#PathVariable(name="transaction-id") Long transactionId);
}
/**
*
*/
package com.mycompany.techtrial;
import java.time.LocalDateTime;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class TransactionControllerImpl implements TransactionController{
/*
* PLEASE DO NOT CHANGE SIGNATURE OR METHOD TYPE OF END POINTS
* Example Post Request : { "book":"Java8 Primer","member":"Test 1" }
*/
#PostMapping(path = "/api/transaction")
public ResponseEntity<Transaction> issueBookToMember(#RequestBody Map<String, String> params){
String book = params.get("book");
String member = params.get("member");
Transaction transaction = new Transaction();
transaction.setId(1L);
transaction.setBook(book);
transaction.setMember(member);
transaction.setDateOfIssue(LocalDateTime.now());
transaction.setDateOfReturn(Transaction.getDefaultReturnDate());
return ResponseEntity.ok().body(transaction);
}
/*
* PLEASE DO NOT CHANGE SIGNATURE OR METHOD TYPE OF END POINTS
*/
#PatchMapping(path= "/api/transaction/{transaction-id}/return")
public ResponseEntity<Transaction> returnBookTransaction(#PathVariable(name="transaction-id") Long transactionId){
String book = "Java8 Primer";
String member = "Test 1";
Transaction transaction = new Transaction();
transaction.setId(1L);
transaction.setBook(book);
transaction.setMember(member);
transaction.setDateOfIssue(LocalDateTime.now().minusDays(10));
transaction.setDateOfReturn(LocalDateTime.now());
return ResponseEntity.ok().body(transaction);
}
}
package com.mycompany.techtrial;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class TransactionControllerTest {
MockMvc mockMvc;
#Mock
private TransactionController transactionController;
#Autowired
private TestRestTemplate template;
#Before
public void setup() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(transactionController).build();
}
#Test
public void testBookIssue() throws Exception {
HttpEntity<Object> transaction = getHttpEntity(
"{\"book\": \"Java8 Primer\", \"member\": \"Test 1\" }");
ResponseEntity<Transaction> response = template.postForEntity(
"/api/transaction", transaction, Transaction.class);
Assert.assertEquals("Java8 Primer", response.getBody().getBook());
Assert.assertEquals("Test 1", response.getBody().getMember());
Assert.assertEquals(200,response.getStatusCode().value());
}
#Test
public void testBookReturnUsingRestTemplate() throws Exception {
Long transactionId = new Long(1);
HashMap<String,Long> uriVariables = new HashMap<String,Long>();
uriVariables.put("transaction-id", transactionId);
Transaction transaction = template.patchForObject(
"/api/transaction/{transaction-id}/return",null, Transaction.class, uriVariables);
Assert.assertEquals(new Long(1), transaction.getId());
//Assert.assertEquals(200,response.getStatusCode().value());
}
#Test
public void testBookReturnUsingMockMvc() throws Exception {
Long transactionId = new Long(1);
HashMap<String,Long> uriVariables = new HashMap<String,Long>();
uriVariables.put("transaction-id", transactionId);
ResultActions obj = mockMvc.perform( MockMvcRequestBuilders
.patch("/api/transaction/{transaction-id}/return",transactionId)
.content("")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON));
System.out.println(obj.getClass());
HttpStatus status = obj.andReturn().getModelAndView().getStatus();
boolean success = status.is2xxSuccessful();
System.out.println("success="+success);
Assert.assertEquals(new Long(1), transactionId);
//Assert.assertEquals(200,response.getStatusCode().value());
}
private HttpEntity<Object> getHttpEntity(Object body) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<Object>(body, headers);
}
}
package com.mycompany.techtrial;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Transaction implements Serializable {
private static final long serialVersionUID = 8951221480021840448L;
private static final LocalDateTime defaultReturnDate = LocalDateTime.of(LocalDate.of(2299, 12, 31), LocalTime.of(12, 0, 0));
Long id;
private String book;
private String member;
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getMember() {
return member;
}
public void setMember(String member) {
this.member = member;
}
//Date and time of issuance of this book
LocalDateTime dateOfIssue;
//Date and time of return of this book
LocalDateTime dateOfReturn;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDateTime getDateOfIssue() {
return dateOfIssue;
}
public void setDateOfIssue(LocalDateTime dateOfIssue) {
this.dateOfIssue = dateOfIssue;
}
public LocalDateTime getDateOfReturn() {
return dateOfReturn;
}
public void setDateOfReturn(LocalDateTime dateOfReturn) {
this.dateOfReturn = dateOfReturn;
}
#Override
public String toString() {
return "Transaction [id=" + id + ", book=" + book + ", member=" + member + ", dateOfIssue=" + dateOfIssue + ", dateOfReturn=" + dateOfReturn + "]";
}
//#PrePersist
void preInsert() {
if (this.dateOfReturn == null)
this.dateOfReturn = defaultReturnDate;
}
public static LocalDateTime getDefaultReturnDate() {
return defaultReturnDate;
}
}
package com.mycompany.techtrial;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MyLibraryApplication {
public static void main(String[] args) {
SpringApplication.run(MyLibraryApplication.class, args);
}
}
It seems to be a known issue with the RestTemplate default Http client.
RestTemplate bug
A workaround for this would be to use the apache httpcomponents httpclient library in the RestTemplateBuilder.setRequestFactory and pass that in the constructor to TestRestTemplate
After that you can use the exchange method on the TestRestTemplate class and do a PATCH request.
Sample code to create TestRestTemplate:
Supplier<ClientHttpRequestFactory> supplier = () -> {
return new HttpComponentsClientHttpRequestFactory();
};
restTemplateBuilder.requestFactory(supplier);
TestRestTemplate testRestTemplate = new TestRestTemplate(restTemplateBuilder);
testRestTemplate.exchange("/api/transaction/{transaction-id}/return",HttpMethod.PATCH,null,Transaction.class,uriVariables);

Vaadin-Grid not displaying the data from the database it is supposed to show

I am writing a Vaadin Spring application and have the problem that the data from the database are not showing in the Grid (= a Vaadin 8 UI-Component for displaying tables).
I have a suspicion as to where the error may be located (see my remarks at the end of this post).
Everything else (apart from the data not showing in the Grid) is working fine. The database table was automatically created with the help of Spring JPA annotations, the Grid is displayed nicely in the UI, etc. ... only the data from the database are not showing up in the Grid.
For this question I created a new mini-project. The code for this mini-project you can find below. The ui simply consists of a Grid, which is supposed to display the content of a database. (Since the Grid doesn't display anything, the UI is basically an empty frame, see the last screenshot).
The problem in this mini-project is the same as in the original (and much larger) project: the data from the database is not showing up in the Grid.
The mini-project is called "demo" and was created with the help of SpringInitializr. The selected dependencies are shown in the following screenshot:
My demo-app consists of 3 little packages: model, database_access and ui:
The model consists of a single class called "Person". Here's the code of this file:
package com.example.demo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Persons")
public class Person {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name;
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;
}
}
The database-access package consists of 3 files:
PersonRepository,
PersonService and
PersonServiceImpl
... whereby PersonServiceImpl is the implementation of the PersonService interface.
Here's PersonRepository:
package com.example.demo.database_acess;
import com.example.demo.model.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.stream.Stream;
#Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {
#Query("SELECT p FROM Person p")
Stream<Person> findAllByCustomQueryAndStream();
}
Here's PersonService:
package com.example.demo.database_acess;
import com.example.demo.model.Person;
import java.util.stream.Stream;
public interface PersonService {
Stream<Person> streamAllPersons();
long countPersons();
}
and here is PersonServiceImpl:
package com.example.demo.database_acess;
import com.example.demo.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.stream.Stream;
#Service
public class PersonServiceImpl implements PersonService {
#Autowired
private PersonRepository personRepository;
#Transactional
public Stream<Person> streamAllPersons() {
return personRepository.findAllByCustomQueryAndStream();
}
public long countPersons() {
return personRepository.count();
}
}
The ui package consists of the following four files:
GUI, PersonsView, PersonsGrid and PersonDataProvider
GUI:
package com.example.demo.ui;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.spring.navigator.SpringViewProvider;
import com.vaadin.ui.Panel;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import org.springframework.beans.factory.annotation.Autowired;
#SpringUI
#Title("Demo App")
#Theme("valo")
public class GUI extends UI {
#Autowired
private SpringViewProvider viewProvider;
#Override
protected void init(VaadinRequest request) {
VerticalLayout rootLayout = new VerticalLayout();
rootLayout.setSizeFull();
setContent(rootLayout);
Panel viewContainer = new Panel();
viewContainer.setSizeFull();
rootLayout.addComponent(viewContainer);
rootLayout.setExpandRatio(viewContainer, 1.0f);
Navigator navigator = new Navigator(this, viewContainer);
navigator.addProvider(viewProvider);
}
}
PersonsView:
package com.example.demo.ui;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener;
import com.vaadin.spring.annotation.SpringView;
import com.vaadin.spring.annotation.UIScope;
import com.vaadin.ui.VerticalLayout;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
#UIScope
#SpringView(name= PersonsView.NAME)
public class PersonsView extends VerticalLayout implements View {
public static final String NAME = "";
#Autowired
private PersonsGrid personsGrid;
#PostConstruct
void init() {
setMargin(false);
addComponent(personsGrid);
personsGrid.setSizeFull();
}
#Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
}
}
PersonsGrid:
package com.example.demo.ui;
import com.example.demo.model.Person;
import com.vaadin.spring.annotation.SpringComponent;
import com.vaadin.ui.Grid;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
#SpringComponent
public class PersonsGrid extends Grid<Person> {
#Autowired
private PersonDataProvider personDataProvider;
#PostConstruct
void init() {
setDataProvider(personDataProvider);
}
}
PersonDataProvider:
package com.example.demo.ui;
import com.example.demo.database_acess.PersonServiceImpl;
import com.example.demo.model.Person;
import com.vaadin.data.provider.AbstractBackEndDataProvider;
import com.vaadin.data.provider.Query;
import com.vaadin.spring.annotation.SpringComponent;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.stream.Stream;
#SpringComponent
public class PersonDataProvider extends AbstractBackEndDataProvider<Person, Void> {
#Autowired
PersonServiceImpl personService;
public Stream<Person> fetchFromBackEnd(Query<Person, Void> query) {
return personService.streamAllPersons();
}
public int sizeInBackEnd(Query<Person, Void> query) {
return (int) personService.countPersons();
}
}
The application.properties file looks as follows:
spring.datasource.url=jdbc:mysql://localhost:3306/demoDB
spring.datasource.username=root
spring.datasource.password=mypassword
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create
I inserted two persons into the database (Bill and George):
However, these persons are not displayed in the grid, as you can see in the following screenshot:
When writing the code for the Grid (PersonGrid) and the DataProvider (PersonDataProvider), I followed examples from the internet (e.g. http://vaadinhelp.co.in/vaadin-dataprovider-example/)
... My suspicion is that in one of these two files (i.e. PersonGrid and PersonDataProvider) something is missing or wrong.
However, I don't know what.
************************************UPDATE****************************************
I added the following two lines to the init-function of the PersonsView-Class:
personsGrid.addColumn(Person::getName).setCaption("Name");
personsGrid.addColumn(Person::getId).setCaption("ID");
After restarting the application, there are now 3 rows in in the grid (one for the header, one for "George" and one for "Bill").
But: the rows are not correctly displayed, as you can see in the following screenshot:
In the upper left corner you can see the beginning of the three rows but there aren't any columns displayed.
What do I have to do for the data to be displayed correctly?
*******************************UPDATE2******************************************
Apparently, some SQL-operation is not allowed after the ResultSet is closed (see screenshot below). I don't know what this means though.

month is set to january in oracle 11g irresptive of any month

I know its a bit weird question. I am passing date dd-mm-yyyy format from my UI and storing that into oracle 11g. but strange thing happened that it is storing it as JAN month only i.e if I pass 16-10-1992 or 10-03-1992 it is storing it as a 16-JAN-1992 way only. please let me know what silly thing I missed out?
Here's my HibernateUtil.java
package assignment.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.springframework.stereotype.Component;
import assignment.service.UserEntity;
#Component
public class HibernateUtil {
private static SessionFactory sessionFactorty=null;
public static SessionFactory getSessionFactory(){
if(sessionFactorty==null){
System.out.println("inside hibernate Util");
Configuration configuration=new Configuration();
configuration.addAnnotatedClass(UserEntity.class);
configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
configuration.setProperty("hibernate.connection.driver_class", "oracle.jdbc.driver.OracleDriver");
configuration.setProperty("hibernate.connection.username", "myDb");
configuration.setProperty("hibernate.connection.password", "Vihang616");
configuration.setProperty("hibernate.connection.url", "jdbc:oracle:thin:#127.0.0.1:1521:myDb");
/*SchemaExport schemaExport=new SchemaExport(configuration);
schemaExport.create(true, true);*/
StandardServiceRegistryBuilder srb=new StandardServiceRegistryBuilder();
srb.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry=srb.build();
sessionFactorty=configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactorty;
}
public static void shutDown(){
if(sessionFactorty!=null)
sessionFactorty.close();
}
}
Here's my USerService.java
package assignment.service;
import org.hibernate.Session;
import org.springframework.stereotype.Component;
import assignment.model.User;
import assignment.util.HibernateUtil;
import assignment.util.ServiceUtil;
#Component
public class UserService {
public Integer saveUser(User user) {
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
UserEntity userEntity=new UserEntity();
userEntity.setDob(ServiceUtil.stringToDateConverter(user.getDob()));
userEntity.setEmail(user.getEmail());
userEntity.setUserName(user.getUserName());
session.save(userEntity);
session.getTransaction().commit();
System.out.println("ID:"+userEntity.getUserId());
session.disconnect();
HibernateUtil.shutDown();
return userEntity.getUserId();
}
}
Here's my SerivceUtl.java
package assignment.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ServiceUtil {
public static Date stringToDateConverter(String string){
SimpleDateFormat sdf=new SimpleDateFormat("dd-mm-yyyy");
System.out.println("dob:"+string);
Date date=new Date();
try {
date=sdf.parse(string);
} catch (ParseException e) {
System.out.println("exception in parsing date");
e.printStackTrace();
}
return date;
}
}
Here's My Entity class
package assignment.service;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="UserDb")
public class UserEntity implements Serializable {
private static final long serialVersionUID = -6620152467355557520L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer userId;
#Column(nullable=false)
private String userName;
#Column(nullable=false)
private String email;
#Column(nullable=false)
#Temporal(TemporalType.DATE)
private Date dob;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
}

JavaFX TableView and ObservableList - How to auto-update the table?

I know questions similar to this have been asked, and on different dates, but I'll put an SSCCE in here and try to ask this simply.
I would like to be able to update the data model, and have any views upon it automatically update, such that any caller updating the model is not aware of whatever views there presently are. This is what I learned/tried so far, and without calling TableView.refresh() it does not update. What am I missing?
main.java:
package application;
import javafx.application.Application;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
public class Main extends Application {
#Override
public void start(Stage stage) {
// data
ObservableList<Crew> data = FXCollections.observableArrayList();
data.addAll(new Crew(1, "A"), new Crew(2, "B"));
// table
TableColumn<Crew, Integer> crewIdCol = new TableColumn<Crew, Integer>("Crew ID");
crewIdCol.setCellValueFactory(new PropertyValueFactory<Crew, Integer>("crewId"));
crewIdCol.setMinWidth(120);
TableColumn<Crew, String> crewNameCol = new TableColumn<Crew, String>("Crew Name");
crewNameCol.setCellValueFactory(new PropertyValueFactory<Crew, String>("crewName"));
crewNameCol.setMinWidth(180);
TableView<Crew> table = new TableView<Crew>(data);
table.getColumns().addAll(crewIdCol, crewNameCol);
table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
// button
Button button = new Button(" test ");
button.setOnAction(ae -> {
// test
StringProperty nameProp = data.get(0).crewName();
if(nameProp.get().equals("A")) {
data.get(0).setCrewName("foo");
// table.refresh();
System.out.println("foo");
} else {
data.get(0).setCrewName("A");
// table.refresh();
System.out.println("A");
}
});
VBox box = new VBox(10);
box.setAlignment(Pos.CENTER);;
box.getChildren().addAll(table, button);
Scene scene = new Scene(box);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Crew.java
package application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Crew {
private final IntegerProperty crewId = new SimpleIntegerProperty();
private final StringProperty crewName = new SimpleStringProperty();
Crew(int id, String name) {
crewId.set(id);
crewName.set(name);
}
public IntegerProperty crewId() { return crewId; }
public final int getCrewId() { return crewId.get(); }
public final void setCrewId(int id) { crewId.set(id); }
public StringProperty crewName() { return crewName; }
public final String getCrewName() { return crewName.get(); }
public final void setCrewName(String name) { crewName.set(name); }
}
Your model class Crew has the "wrong" name for the property accessor methods. Without following the recommended method naming scheme, the (somewhat legacy code) PropertyValueFactory will not be able to find the properties, and thus will not be able to observe them for changes:
package application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Crew {
private final IntegerProperty crewId = new SimpleIntegerProperty();
private final StringProperty crewName = new SimpleStringProperty();
Crew(int id, String name) {
crewId.set(id);
crewName.set(name);
}
public IntegerProperty crewIdProperty() { return crewId; }
public final int getCrewId() { return crewId.get(); }
public final void setCrewId(int id) { crewId.set(id); }
public StringProperty crewNameProperty() { return crewName; }
public final String getCrewName() { return crewName.get(); }
public final void setCrewName(String name) { crewName.set(name); }
}
Alternatively, just implement the callback directly:
crewIdCol.setCellValueFactory(cellData -> cellData.getValue().crewIdProperty());
in which case the compiler will ensure that you use an existing method name for the property.

Trouble with BeanValidation

I am trying to follow the example in https://jersey.java.net/documentation/latest/bean-validation.html#d0e13678, esp. section 18.4.3. I want to disallow json where Foo.number is missing. But my test returns status 200. Here is the full text of my test (I do have the jersey-bean-validation artifact in my pom):
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class DeleteMe extends JerseyTest {
#Path("/")
public static class Resource {
#POST
#Produces("application/json")
public Foo post(#Valid Foo foo) {
return foo;
}
}
public static class Foo {
#NotNull
private Integer number;
public void setNumber(final Integer number) {
this.number = number;
}
public Integer getNumber() {
return number;
}
}
#Override
protected Application configure() {
return new ResourceConfig(Resource.class)
.register(JacksonFeature.class);
}
#Override
protected void configureClient(final ClientConfig config) {
config.register(JacksonFeature.class);
}
#Test
public void testEntityFail() throws Exception {
Foo foo = new Foo();
Response response = target().request().post(javax.ws.rs.client.Entity.json(foo));
//I get 200 here...but foo is no good
assertTrue("Status "+response.getStatus(),response.getStatus() == 400);
}
}
PEBKAC -- I will leave the question up in case someone is getting started with validation and needs a dumbed-down "Hello World" test

Resources