I'm trying to make my first simple project with Dropwizard. I have a MySQL-database, and the idea is to get the data (companies) from there and represent it as JSON. I have followed the Getting started page by Dropwizard and this tutorial to get connected to database with Hibernate.
The idea is that URL "/companies" serves all the companies as JSON, and it is working fine.
URL "/companies/{id}" is supposed to give a single company with given id, but every request gives code 400 and message "Unable to process JSON". The details field in the response says
"No serializer found for class
jersey.repackaged.com.google.common.base.Present and no properties
discovered to create BeanSerializer (to avoid exception, disable
SerializationFeature.FAIL_ON_EMPTY_BEANS) )"
If I give an id of company that does not exist in database, the class in mentioned message changes to
jersey.repackaged.com.google.common.base.Absent
The company class is here:
public class Company {
#ApiModelProperty(required = true)
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "name")
private String name;
#Column(name = "address")
private String address;
#Column(name = "zipcode")
private String zipCode;
#Column(name = "email")
private String eMail;
#Column(name = "mobile")
private String mobile;
public Company() {
}
public Company (String name, String address, String zipCode, String eMail, String mobile) {
this.name = name;
this.address = address;
this.zipCode = zipCode;
this.eMail = eMail;
this.mobile = mobile;
}
#JsonProperty
public long getId() {
return id;
}
#JsonProperty
public void setId(long id) {
this.id = id;
}
#JsonProperty
public String getName() {
return name;
}
#JsonProperty
public void setName(String name) {
this.name = name;
}
#JsonProperty
public String getAddress() {
return address;
}
#JsonProperty
public void setAddress(String address) {
this.address = address;
}
#JsonProperty
public String getZipCode() {
return zipCode;
}
#JsonProperty
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
#JsonProperty
public String geteMail() {
return eMail;
}
#JsonProperty
public void seteMail(String eMail) {
this.eMail = eMail;
}
#JsonProperty
public String getMobile() {
return mobile;
}
#JsonProperty
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
DAO is here:
public class CompanyDAO extends AbstractDAO<Company> {
public CompanyDAO(SessionFactory sessionFactory) {
super(sessionFactory);
}
public List<Company> findAll() {
return list(namedQuery("com.webapp.project.core.Company.findAll"));
}
public Optional<Company> findById(long id) {
return Optional.fromNullable(get(id));
}
}
Application class:
public class HelloWorldApplication extends Application<HelloWorldConfiguration> {
public static void main(String[] args) throws Exception {
new HelloWorldApplication().run(args);
}
#Override
public String getName() {
return "hello-world";
}
/**
* Hibernate bundle.
*/
private final HibernateBundle<HelloWorldConfiguration> hibernateBundle
= new HibernateBundle<HelloWorldConfiguration>(
Company.class
) {
#Override
public DataSourceFactory getDataSourceFactory(
HelloWorldConfiguration configuration
) {
return configuration.getDataSourceFactory();
}
};
#Override
public void initialize(Bootstrap<HelloWorldConfiguration> bootstrap) {
bootstrap.addBundle(new SwaggerBundle<HelloWorldConfiguration>() {
#Override
protected SwaggerBundleConfiguration getSwaggerBundleConfiguration(HelloWorldConfiguration sampleConfiguration) {
return sampleConfiguration.getSwaggerBundleConfiguration();
}
});
bootstrap.addBundle(hibernateBundle);
}
#Override
public void run(HelloWorldConfiguration configuration,
Environment environment) {
final CompanyDAO companyDAO = new CompanyDAO(hibernateBundle.getSessionFactory());
environment.jersey().register(new CompaniesResource(companyDAO));
environment.jersey().register(new JsonProcessingExceptionMapper(true));
}
}
Configuration class:
public class HelloWorldConfiguration extends Configuration {
#Valid
#NotNull
private DataSourceFactory database = new DataSourceFactory();
#NotNull
private SwaggerBundleConfiguration swaggerBundleConfiguration;
#JsonProperty("swagger")
public void setSwaggerBundleConfiguration (SwaggerBundleConfiguration conf) {
this.swaggerBundleConfiguration = conf;
}
#JsonProperty("swagger")
public SwaggerBundleConfiguration getSwaggerBundleConfiguration () {
return swaggerBundleConfiguration;
}
#JsonProperty("database")
public void setDataSourceFactory(DataSourceFactory factory) {
this.database = factory;
}
#JsonProperty("database")
public DataSourceFactory getDataSourceFactory() {
return database;
}
}
Resource class:
#Path("/companies")
#Api("Companies")
#Produces(MediaType.APPLICATION_JSON)
public class CompaniesResource {
private CompanyDAO companyDAO;
public CompaniesResource(CompanyDAO companyDAO) {
this.companyDAO = companyDAO;
}
#GET
#ApiOperation(
value = "Gives list of all companies",
response = Company.class,
code = HttpServletResponse.SC_OK
)
#UnitOfWork
public List<Company> findAll () {
return companyDAO.findAll();
}
#GET
#Path("/{id}")
#UnitOfWork
public Optional<Company> getById(#PathParam("id") LongParam id) {
return companyDAO.findById(id.get());
}
}
I would be happy for any responses!
I was getting the error Unable to Process JSON.
Troubleshooted more than 4 hours until I found the problem.
The error is caused because of Enum getter.
If you are using Enum fields/getters/setters in your POJO, Jackson will fail to map your JSON to Java Object, and it will crash, leading to the mentioned error.
Looks like your json marshaller is not able to marshall google's Optional class. Try to return Company from the controller, and not Optional:
#GET
#Path("/{id}")
#UnitOfWork
public Company getById(#PathParam("id") LongParam id) {
return companyDAO.findById(id.get()).get();
}
Related
Repository
*As I am trying to enter details of user but i am getting bean Exception i don't what i have missed
from repository interface i have implements JPA and i triad with crud as well . I dint mention any controller class yet
public interface UserRepository extends JpaRepository<User,Long> {
public User findByName(String username);
}
UserModel
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String email;
private Date DOB;
private String Address;
public User() {
}
public User(Long id, String username, String email, Date DOB, String address) {
this.id = id;
this.username = username;
this.email = email;
this.DOB = DOB;
Address = address;
}
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 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 String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
}
UserService
Userservice i have given
public interface UserService {
//Creating User
public User CreateUser(User user) throws Exception;
}
ServiceImp
public class UserServiceImp implements UserService {
#Autowired
private UserRepository userData;
//Creating user
#Override
public User CreateUser(User user) throws Exception {
User local=this.userData.findByName(user.getUsername());
if(local!=null)
{
System.out.println("User is already present!!");
throw new Exception("User is already there");
}
else {
local=this.userData.save(user);
}
return local;
}
}
Main Class
This is the main class
#SpringBootApplication
public class UserInformationApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(UserInformationApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("starting Application");
}
}
Changing this
Use for Spring Version 2.x :
import javax.persistence.*;
to
Use for Spring Version 3.x :
import jakarta.persistence.*;
Worked for me
I have built a REST API using Spring Boot Data REST. I'm using an embeddedId and have also implemented a BackendIdConverter.
Below is my Embeddable class
#Embeddable
public class EmployeeIdentity implements Serializable {
#NotNull
#Size(max = 20)
private String employeeId;
#NotNull
#Size(max = 20)
private String companyId;
public EmployeeIdentity() {}
public EmployeeIdentity(String employeeId, String companyId) {
this.employeeId = employeeId;
this.companyId = companyId;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EmployeeIdentity that = (EmployeeIdentity) o;
if (!employeeId.equals(that.employeeId)) return false;
return companyId.equals(that.companyId);
}
#Override
public int hashCode() {
int result = employeeId.hashCode();
result = 31 * result + companyId.hashCode();
return result;
}
}
Here's my Employee model
#Entity
#Table(name = "employees")
public class Employee {
#EmbeddedId
private EmployeeIdentity id;
#NotNull
#Size(max = 60)
private String name;
#NaturalId
#NotNull
#Email
#Size(max = 60)
private String email;
#Size(max = 15)
#Column(name = "phone_number", unique = true)
private String phoneNumber;
public Employee() {}
public Employee(EmployeeIdentity id, String name, String email, String phoneNumber) {
this.id = id;
this.name = name;
this.email = email;
this.phoneNumber = phoneNumber;
}
public EmployeeIdentity getId() {
return id;
}
public void setId(EmployeeIdentity id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
And to have resource links generated properly using my embedded id instead of a qualified class name
#Component
public class EmployeeIdentityIdConverter implements BackendIdConverter {
#Override
public Serializable fromRequestId(String id, Class<?> aClass) {
String[] parts = id.split("_");
return new EmployeeIdentity(parts[0], parts[1]);
}
#Override
public String toRequestId(Serializable source, Class<?> aClass) {
EmployeeIdentity id = (EmployeeIdentity) source;
return String.format("%s_%s", id.getEmployeeId(), id.getCompanyId());
}
#Override
public boolean supports(Class<?> type) {
return Employee.class.equals(type);
}
}
And here's my repository code
#RepositoryRestResource(collectionResourceRel = "employees", path = "employees")
public interface EmployeeRepository extends PagingAndSortingRepository<Employee, EmployeeIdentity> {
}
This works fine with GET requests but I need to be able to POST. The first thing I noticed that when I do a POST with the json
{
"id": {
"employeeId": "E-267",
"companyId": "D-432"
},
"name": "Spider Man",
"email": "spman#somedomain.com",
"phoneNumber": "+91-476253455"
}
This doesn't work. EmployeeIdentityIdConverter#fromRequestId throws a null pointer exception because the string parameter is null. So I added a null check and return default EmployeeIdentity when id is null. As described by this answer https://stackoverflow.com/a/41061029/4801462
Modified EmployeeIdentityIdConverter#fromRequestId
#Override
public Serializable fromRequestId(String id, Class<?> aClass) {
if (id == null) {
return new EmployeeIdentity();
}
String[] parts = id.split("_");
return new EmployeeIdentity(parts[0], parts[1]);
}
But this raised another problem. My implementations for hashCode and equals now through null pointer exceptions since the default constructor was used and the employeeId and companyId are null.
In an attempt to fix this, I gave default values to employeeId and companyId
**Modified Employee#Employee() constructor*
public Employee() {
this.employeeId = "";
this.companyId = "";
}
NOTE
I am not even sure of what I was doing above. I was just trying to fix the small problems as they occurred.
By the way if you guessed this didn't work then you're right. While I didn't get an error and the request was successful, I didn't get the behavior I expected. A new entry was created with empty employeeId and companyId.
How do make POST to REST API whose model uses #EmbeddedId with spring boot data rest?
Here is an other solution. (Still not perfect though.)
Expose the id for your Employee class:
#Configuration
protected class MyRepositoryRestConfigurer implements RepositoryRestConfigurer {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(ThemeMessage.class);
}
}
Add the following line to your converter (during POST requests the id will be null):
#Override
public Serializable fromRequestId(String id, Class<?> aClass) {
if(id==null) {
return null;
}
String[] parts = id.split("_");
return new EmployeeIdentity(parts[0], parts[1]);
}
The following POST request then will work:
{
"id": {
"employeeId": "E-267",
"companyId": "D-432"
},
"name": "Spider Man",
"email": "spman#somedomain.com",
"phoneNumber": "+91-476253455"
}
However, the id field will be exposed in all of the responses. But maybe it's not a real problem, because when you use a composite id it usually means that the id is not only an abstract identifier, but its parts have meaningful content which should appear in the entity body.
Actually, I'm thinking of adding these lines to my own code too .... :)
I had a similar problem and I couldn't find a solution for creating new entities via the POST /entities endpoint.
However, you can also create a new entity via PUT /entities/{newId} endpoint. And the converter works fine for these endpoints.
I also completely denied the POST endpoint avoiding the 500 responses:
#PostMapping(value = "/themeMessages")
public ResponseEntity<Void> postThemeMessage() {
return new ResponseEntity<>(HttpStatus.METHOD_NOT_ALLOWED);
}
I am new with using spring boot + jersey api + JPA.
I hava three entity that uses one to many bidirectional mapping. When i used spring boot + jersey api+ JPA I get error :
failed to lazily initialize a collection of role: com.kavinaam.GSTbilling.entity.Country.states, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.kavinaam.GSTbilling.entity.City["states"]->com.kavinaam.GSTbilling.entity.States["countyId"]->com.kavinaam.GSTbilling.entity.Country["states"])
I have added my entity, dao , services and end point.
#Entity
#Table(name="country")
public class Country implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private int id;
#Column(name="countryName")
private String countryName;
#OneToMany(mappedBy = "countyId",cascade = CascadeType.ALL)
private Set<States> states;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Set<States> getStates() {
return states;
}
public void setStates(Set<States> states) {
this.states = states;
}
}
My state class:
#Entity
#Table(name="states")
public class States implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private int id;
#ManyToOne
#JoinColumn(name="countyId")
private Country countyId;
#Column(name="stateName")
private String stateName;
#OneToMany(mappedBy = "states", cascade = CascadeType.ALL)
private Set<City> city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Country getCountyId() {
return countyId;
}
public void setCountyId(Country countyId) {
this.countyId = countyId;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public Set<City> getCity() {
return city;
}
public void setCity(Set<City> city) {
this.city = city;
}
}
My city class:
#Entity
#Table(name="cities")
public class City implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
private int id;
#ManyToOne
#JoinColumn(name="stateId")
private States states;
#Column(name="cityName")
private String cityName;
#Column(name="zip")
private String zip;
public void setId(int id) {
this.id = id;
}
public void setZip(String zip) {
this.zip = zip;
}
public States getStates() {
return states;
}
public void setStates(States states) {
this.states = states;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getZip() {
return zip;
}
public int getId() {
return id;
}
}
My DAO:
#Transactional
#Repository
public class GSTCityDAO implements IGSTCityDAO {
#PersistenceContext
private EntityManager entityManager;
//#SuppressWarnings("unchecked")
#Override
public List<City> getAllCities() {
//Session session = sessionFactory.getCurrentSession();
String hql = "FROM City as ct ORDER BY ct.id";
List<City> l = entityManager.createQuery(hql,City.class).getResultList();
return l;
}
#Override
public City getCityById(int cityId) {
return entityManager.find(City.class, cityId);
}
#SuppressWarnings("unchecked")
#Override
public List<City> getCityByStateId(States stateId) {
String getcitybystate = " FROM City as c WHERE c.states = ?";
return (List<City>) entityManager.createQuery(getcitybystate).setParameter(1, stateId).getResultList();
}
#Override
public void addCity(City city) {
entityManager.persist(city);
}
#Override
public void updateCity(City city) {
City cityctl = getCityById(city.getId());
cityctl.setCityName(city.getCityName());
cityctl.setZip(city.getZip());
cityctl.setStates(city.getStates());
entityManager.flush();
}
#Override
public void deleteCity(int cityId) {
entityManager.remove(getCityById(cityId));
}
#Override
public boolean cityExists(String name, String zip) {
String hql = "FROM City WHERE cityName = ? and zip = ?";
int count = entityManager.createQuery(hql).setParameter(1,name).setParameter(2, zip).getResultList().size();
return count > 0 ? true : false;
}
}
Services:
#Service
public class GSTCityService implements IGSTCityService {
#Autowired
private IGSTCityDAO cityDAO;
#Override
public List<City> getAllCities() {
List<City> l = cityDAO.getAllCities();
Hibernate.initialize(l);
return l;
}
public List<City> getCityByStateId(States stateId) {
return cityDAO.getCityByStateId(stateId);
}
#Override
public City getCityById(int cityId) {
City city = cityDAO.getCityById(cityId);
return city;
}
#Override
public synchronized boolean addCity(City city) {
if(cityDAO.cityExists(city.getCityName(), city.getZip())){
return false;
}else{
cityDAO.addCity(city);
return true;
}
}
#Override
public void updateCity(City city) {
cityDAO.updateCity(city);
}
#Override
public void deleteCity(int cityId) {
cityDAO.deleteCity(cityId);
}
}
End Point:
#Component
#Path("/")
public class Test {
private static final Logger logger = LoggerFactory.getLogger(Test.class);
#Autowired
private IGSTCityService cityService;
#GET
#Path("/hi")
#Produces(MediaType.APPLICATION_JSON)
public Response hello(){
return Response.ok("Hello GST").build();
}
#GET
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
public Response getAllDate(){
List<City> list = cityService.getAllCities();
for(City city: list){
System.out.println(city);
}
return Response.ok(list).build();
}
#GET
#Path("/test/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response getAllDateBySome(#PathParam("id") Integer id){
States state = new States();
state.setId(id);
List<City> list = cityService.getCityByStateId(state);
return Response.ok(list).build();
}
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response getDataById(#PathParam("id")Integer id){
City citl = cityService.getCityById(id);
return Response.ok(citl).build();
}
#POST
#Path("/add")
#Consumes(MediaType.APPLICATION_JSON)
public Response addData(City city){
boolean isAdded = cityService.addCity(city);
if(!isAdded){
return Response.status(Status.CONFLICT).build();
}
return Response.created(URI.create("/gst/"+ city.getId())).build();
}
#PUT
#Path("/update")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response updateCountry(City city){
cityService.updateCity(city);
return Response.ok(city).build();
}
#DELETE
#Path("/{id}")
#Consumes(MediaType.APPLICATION_JSON)
public Response deleteCountry(#PathParam("id")Integer id){
cityService.deleteCity(id);
return Response.noContent().build();
}
}
I am using import org.springframework.transaction.annotation.Transactional; for transnational in DAO. Also I can not use #PersistenceContext(type=PersistenceContextType.EXTENDED) and fetch type Eager because I get error of Maximum stack size exceeded
I solved it by using the #JsonBackReference on OneToMany relationship. The problem is with the Serialization and Deserialization.
" the property annotated with #JsonManagedReference annotation is handled normally (serialized normally, no special handling for deserialization) and the property annotated with #JsonBackReference annotation is not serialized; and during deserialization, its value is set to instance that has the "managed" (forward) link."
You should do one or both of the following:
1) Move the #Transactional from DAO to Service. Thats a good idea in general as usually are still processing the result entities in some way on that layer.
2) Fetch the dependencies in the queries explicitly:
select ct FROM City as ct inner join fetch ct.states s ORDER BY ct.id
I am trying to retrieve data from mongodb via spring framework.
At first I made return type Map<String, Object>, but I decided to change to User value object.
Below is the class for User VO
#Document(collection = "user")
public class User {
#Id
#Field(value="id")
private String id;
#Field(value="name")
private String name;
#Field(value="password")
private String password;
#Field(value="professional")
private String professional;
#Field(value="email")
private String email;
#Field(value="gravatar")
private String gravatar;
#PersistenceConstructor
public User(String id, String name, String password, String professional, String email, String gravatar) {
super();
this.id = id;
this.name = name;
this.password = password;
this.professional = professional;
this.email = email;
this.gravatar = gravatar;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getProfessional() {
return professional;
}
public void setProfessional(String professional) {
this.professional = professional;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGravatar() {
return gravatar;
}
public void setGravatar(String gravatar) {
this.gravatar = gravatar;
}
};
and Here is #repository to retrieve data
#Repository
public class MongoMemberDao implements CommonDao<String, Map<String, Object>, Exception> {
#Autowired
MongoTemplate template;
final String COLLECTION_NAME = "user";
#SuppressWarnings("unchecked")
#Override
public Map<String, Object> read(String key) throws Exception {
Query findQuery = new Query();
findQuery.addCriteria(Criteria.where("id").is(key));
return template.findOne(findQuery, Map.class, COLLECTION_NAME);
}
public User readByDocument(String id) throws Exception {
Query findOneQuery = new Query();
findOneQuery.addCriteria(Criteria.where("id").is(id));
return template.findOne(findOneQuery, User.class, COLLECTION_NAME);
}
};
read method returns fine, but readByDocument does not(returns null not User instance). I read official document. But I do not get any clue of it.
FYI, The parameter Query looks same for both.
Query: { "id" : "system"}, Fields: null, Sort: null
I want to know why readByDocument returns null
Thanks.
---- Edit
Follow is my Database Config
#Configuration
public class MongoConfig extends AbstractMongoConfiguration {
private final String MONGO_URL = "127.0.0.1";
private final Integer MONGO_PORT = 27017;
#Override
protected String getDatabaseName() {
return "tfarm";
}
#Override
// #Bean
public Mongo mongo() throws Exception {
return new MongoClient(MONGO_URL, MONGO_PORT);
}
}
And I added this to WebApplictaionInitializer implement.
For current solution
I found follow on official site
A field annotated with #Id (org.springframework.data.annotation.Id)
will be mapped to the _id field.
A field without an annotation but named id will be mapped to the _id
field.
The default field name for identifiers is _id and can be customized
via the #Field annotation.
So I changed my VO like...
#Document(collection = "user")
public class User {
#Id
private ObjectId _id;
#Field(value="id")
private String id;
#Field(value="name")
private String name;
#Field(value="password")
private String password;
#Field(value="professional")
private String professional;
#Field(value="email")
private String email;
#Field(value="gravatar")
private String gravatar;
#PersistenceConstructor
public User(String id, String name, String password, String professional, String email, String gravatar) {
super();
this.id = id;
this.name = name;
this.password = password;
this.professional = professional;
this.email = email;
this.gravatar = gravatar;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ObjectId get_id() {
return _id;
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getProfessional() {
return professional;
}
public void setProfessional(String professional) {
this.professional = professional;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGravatar() {
return gravatar;
}
public void setGravatar(String gravatar) {
this.gravatar = gravatar;
}
};
Added ObjectId. In alternative, just removing #Id annotation works fine too. However
#Id
#Field(value="id")
String id;
will not work. Thanks for help.
I am building a webapp using Restful webservice using angularJs + spring. Can anybody tell how to make date field readable in the UI ? Also, I am not getting the last field values that is 'STATUS'. Below is the code for the same.
Basic Entity class/ model class
#Entity
#Table(name="User",schema="test")
public class User implements java.io.Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String firstName;
private String lastName;
private Date creation_time;
private Date last_update_time;
private String email;
private String mobile;
private String status;
#Id
#Column(name="ID", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATION_TIME", nullable = false, length = 19)
public Date getCreation_time() {
return creation_time;
}
public void setCreation_time(Date creation_time) {
this.creation_time = creation_time;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_MOD_TIME", nullable = false, length = 19)
public Date getLast_update_time() {
return last_update_time;
}
public void setLast_update_time(Date last_update_time) {
this.last_update_time = last_update_time;
}
#Column(name="EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="MOBILE")
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public void setStatus(String status) {
this.status = status;
}
#Column(name="STATUS")
public String getStatus(String status){
return status;
}
}
Controller class
#RestController
public class UserController {
#Autowired
UserService userService;
private static Logger logger = Logger.getLogger(UserController.class);
#RequestMapping(value="/users",method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userService.getAllUserService();
return users;
}
}
DAO interface
public interface UserDAO {
public List<User> getAllUser();
}
DAO Implementation class
#Component
#Transactional(readOnly = true)
public class UserDAOImpl implements UserDAO {
#Autowired
private SessionFactory sessionFactory;
Session session = null;
private void assignSessionLocalVariable(){
if(session == null || !session.isOpen()){
try{
session = sessionFactory.openSession();
}catch(Exception e){session = null;
e.printStackTrace();
}
}
}
#Override
public List<User> getAllUser() {
List<User> user=null;
assignSessionLocalVariable();
if(session!=null){
try{
String q="from User";
Query query = session.createQuery(q);
user = query.list();
}catch(Exception e){
e.printStackTrace();
}
}
session.close();
return user;
}
public void closeSessionObjects(){
if(null != session) session.clear();
}
}
Service interface
public interface UserService {
public List<User> getAllUserService();
}
Service implementation class
#Service
public class UserServiceImpl implements UserService {
#Autowired
UserDAO userDAO;
#Override
public List<User> getAllUserService() {
return userDAO.getAllUser();
}
}
App.js
var user=angular.module('userApp', ['']);
user.controller('userController',function($scope,$http){
var urlBase="http://localhost:8080/UserDetail";
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get(urlBase+"/users")
.success(function(data){
$scope.users = data;
});
});
moment is pretty awesome for formatting datetime
Example for your case:
Let's say the datetime looks like 2015-11-11T22:21:37+00:00. Obviously this does not look very readable. We can change it to something better by making a moment object and using the format function.
moment(2015-11-11T22:21:37+00:00).format("MM/DD/YYYY") would output 11/11/2015