Jersey cannot deserialize java.util.UUID out of String in request object - java

I have an endpoint which accepts a DriverJson class instance as http request payload. The DriverJson class has a property userId which is of type java.util.UUID.
The problem is that Jersey cannot deserialize UUID string into UUID object. When I debug and inspected driverJson, userId1 property is null (luckily it does not throw exception). I have read this article (article) that explains that classes that have fromString(String string) method (java.util.UUID has it) or have constructor with one (String) argument are deserialized by Jersey automatically (without writing any additional deserializer classes). If I change UUID type to String and I convert it my self (UUID.fromString(userId)) it's working perfectly.
In addition I use a #PathParam UUID arguments in some of my endpoints and they are working perfectly (as expected).
Below is my code:
My resource endpoint:
#POST
public Response add(DriverJson driverJson) {
DriverJson driver = service.add(driverJson);
return Response.status(Response.Status.CREATED).entity(driver).build();
}
My Driver class:
#XmlRootElement
public class DriverJson {
private UUID id;
private String name;
private UUID userId;
public DriverJson() {}
public DriverJson(UUID id, String name, UUID userId){
this.id = id;
this.name = name;
this.userId = userId;
}
/// getters & setters /////////
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UUID getUserId() {
return userId;
}
public void setUserId(UUID userId) {
this.userId = userId;
}
}
My JSON request object:
{
"name" : "John",
"userId" : "ff06c5a4-135c-40b7-83f3-3648ec035efc"
}
I am using the standard Jersey archetype (version 2.23.2) with the following dependencies:
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.50</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>16.0.1</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
</dependencies>

AFAIK you can fix it by using custom XmlAdapter:
public class UUIDAdapter extends XmlAdapter<String, UUID> {
#Override
public UUID unmarshal(String v) throws Exception {
return UUID.fromString(v);
}
#Override
public String marshal(UUID v) throws Exception {
return v.toString();
}
}
And then mark your fields with #XmlJavaTypeAdapter annotation
#XmlRootElement
public class DriverJson {
#XmlJavaTypeAdapter(UUIDAdapter.class)
private UUID id;
#XmlJavaTypeAdapter(UUIDAdapter.class)
private UUID userId;
/* ... */
}

Related

MOXy XPath unmarshalling Element is null

Im trying to unmarshall the camunda:property elements into a List using XPath to skip the unnecessary wrapper elements. Unfortunately my propertyList is always null. This is located in the Task Class. Any help would be greatly appreciated.
Edit#1:
I followed the following links who were supposed to help with my problem unfortunately without success. http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html which is the official guide. Apparently there are some challenges with the maven pom.xml file. I suspect that the problem lies inside the pom file.
I followed this guide https://www.javacodegeeks.com/2012/07/eclipselink-moxy-as-jaxb-provider.html but still did not get it to work.
pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>BPMN-Marshaller</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<repositories><repository>
<id>EclipseLink Repo</id>
<url>http://download.eclipse.org/rt/eclipselink/maven.repo</url>
<name>EclipseLink Repo</name>
</repository></repositories>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.moxy</artifactId>
<version>3.0.0-M1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
<!-- Runtime, com.sun.xml.bind module -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.2</version>
</dependency>
</dependencies>
</project>
jaxb.properties file in the same package and folder as my java classes(see attached image with name "Project Structure")
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
package-info.java file
#XmlSchema(namespace="http://www.omg.org/spec/BPMN/20100524/MODEL", elementFormDefault=XmlNsForm.QUALIFIED, xmlns = {#XmlNs(prefix="bpmn", namespaceURI="http://www.omg.org/spec/BPMN/20100524/MODEL")
,#XmlNs(prefix = "camunda", namespaceURI = "http://camunda.org/schema/1.0/bpmn")})
package bpmn;
import javax.xml.bind.annotation.*;
xml file snippet
<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:dc="http://www.omg.org/spec/DD/20100524/DC" xmlns:camunda="http://camunda.org/schema/1.0/bpmn" xmlns:di="http://www.omg.org/spec/DD/20100524/DI" id="Definitions_13d3a6z" targetNamespace="http://bpmn.io/schema/bpmn" exporter="Camunda Modeler" exporterVersion="4.1.1">
<bpmn:process id="Process_1tovjba" isExecutable="true">
<bpmn:startEvent id="StartEvent_1">
<bpmn:outgoing>Flow_06i118e</bpmn:outgoing>
</bpmn:startEvent>
<bpmn:task id="Activity_1d3friu" name="Task 1">
<bpmn:extensionElements>
<camunda:properties>
<camunda:property name="start_date" value="01-04-2018" />
<camunda:property name="duration" value="5" />
</camunda:properties>
</bpmn:extensionElements>
<bpmn:incoming>Flow_06i118e</bpmn:incoming>
<bpmn:outgoing>Flow_0linmbs</bpmn:outgoing>
</bpmn:task>
Definitions Class
#XmlRootElement
public class Definitions {
private String id;
private Process process;
public Definitions(){};
public Definitions(String id, Process process){
super();
this.id = id;
this.process = process;
}
#XmlAttribute
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#XmlElement
public Process getProcess() {
return process;
}
public void setProcess(Process process) {
this.process = process;
}
#Override
public String toString(){
return "Definitions [id23=" + id + ", process=23499999999999999" + process + "]";
}
}
Process Class
public class Process {
private String id;
private List<Task> taskList;
private List<SequenceFlow> sequenceFlowList;
public Process(){};
public Process(String id, List<Task> taskList, List<SequenceFlow> sequenceFlowList){
super();
this.id = id;
this.taskList = taskList;
this.sequenceFlowList = sequenceFlowList;
}
#XmlAttribute
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#XmlElement(name = "task")
public List<Task> getTaskList() {
return taskList;
}
public void setTaskList(List<Task> taskList) {
this.taskList = taskList;
}
#XmlElement(name = "sequenceFlow")
public List<SequenceFlow> getSequenceFlowList() {
return sequenceFlowList;
}
public void setSequenceFlowList(List<SequenceFlow> sequenceFlowList) {
this.sequenceFlowList = sequenceFlowList;
}
}
Task Class
public class Task {
private String id;
private String name;
private List<Property> propertyList;
public Task(){}
public Task(String id, String name, List<Property> propertyList){
super();
this.id = id;
this.name = name;
this.propertyList = propertyList;
}
#XmlAttribute
#JsonProperty("text")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlAttribute
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#XmlElement(name = "property")
#XmlPath("bpmn:extensionElements/camunda:properties/camunda:property")
public List<Property> getPropertyList() {
return propertyList;
}
public void setPropertyList(List<Property> propertyList) {
this.propertyList = propertyList;
}
}
Property Class
public class Property {
private String name;
private String value;
public Property(){}
public Property(String name, String value) {
super();
this.name = name;
this.value = value;
}
#XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#XmlAttribute
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Main Class
public class XMLToObject {
public static void main(String[] args) {
try {
File file = new File("process.bpmn");
JAXBContext jaxbContext = JAXBContext.newInstance(Definitions.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Definitions definitions = (Definitions) jaxbUnmarshaller.unmarshal(file);
System.out.println(definitions.getProcess().getTaskList().get(0).getPropertyList());
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Project Structure
I made the following changes to your approach, and I am able to access the duration and start_date properties data from your XML file.
I am using OpenJDK 14, by the way. But this approach runs OK using version 8 also.
The POM I am using has the following dependencies:
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
<!--
Use 2.3.1 below to prevent "illegal
reflective access operation" warnings.
-->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.7.6</version>
</dependency>
(I skipped the Jackson dependency just for this test.)
I also added the following section at the end of my POM, to handle the properties file:
<!-- to copy the jaxb.properties file to its class package: -->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
</build>
This ensures the properties file is deployed to the correct location with its related class files.
I added the code to check for which JAXB provider is being used - just as a positive confirmation:
private void checkProvider() throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(Definitions.class);
String jaxbContextImpl = jc.getClass().getName();
if(MOXY_JAXB_CONTEXT.equals(jaxbContextImpl)) {
System.out.println("EclipseLink MOXy");
} else if(METRO_JAXB_CONTEXT.equals(jaxbContextImpl)) {
System.out.println("Metro");
} else {
System.out.println("Other");
}
}
I modified the code to loop through the properties data, to explicitly print the final properties values:
List<Property> props = definitions.getProcess().getTaskList().get(0).getPropertyList();
props.forEach(prop -> {
System.out.println(prop.getName() + " - " + prop.getValue());
});
//System.out.println(definitions.getProcess().getTaskList().get(0).getPropertyList());
The resulting output is:
EclipseLink MOXy
start_date - 01-04-2018
duration - 5

#Valid #ModelAttribute not working properly

I have this controller
#Controller
public class EmpleadoController {
#Autowired
private EmpleadoService servicio;
#PostMapping("/empleado/new/submit")
public String nuevoEmpleadoSubmit(#Valid #ModelAttribute("empleadoForm") Empleado empleadoForm, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return "formulario";
}else {
servicio.add(empleadoForm);
return "redirect:/empleado/list";
}
}
}
With this model
package com.alexotero.spring.model;
import javax.validation.constraints.Email;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
public class Empleado {
#Min(0)
private long id;
#NotEmpty
private String nombre;
#Email
private String email;
private String telefono;
//Constructors getters setters and stuff
I've also added this dependency to the pom.xml
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
It doesn't matter what i introduce in the form, the controller never detects any error. Always adds the object to the List(in the service) and redirects to the list.html. I cannot find where is the problem.
For my case, I removed this dependency
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
and added
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
I think they both conflict with each other.

Using customized ObjectWriter with Jersey

I am developing a REST webservice. Jersey as jax-rs provider and Jackson for serialization/deserialization. I also develop the client based on Retrofit2.
My class hierarchy is provided by a third-party library and all classes descend from a root base class BaseObject. Some of those classes have undesirable getters, e.g. isEmpty, that I want to ignore on serialization (Note that it is important that they do not get serialized at all and using FAIL_ON_UNKNOWN_PROPERTIES on deserialization is not enough in my case).
I have used Jackson #JsonFilter on BaseClass using Mixins. To apply a filter, as far as I know, one has to use the following:
new ObjectMapper().writer(filterProvider).writeValueAsString...
Everything is ok up to here: the undesired property is successfully filtered from the produced json.
Now I have to configure Jersey and Retrofit2 to use my customized json serializer/deserializer.
For Jersey, serialization/deserialization can be configured using a Provider class that implements ContextResolver<ObjectMapper> and returning customized ObjectMapper in getContext(Class<?> type) method.
Similarly in Retrofit2, by using
Retrofit.Builder().addConverterFactory(JacksonConverterFactory.create(objectMapper)), one can customize serialization/deserialization.
THE PROBLEM IS THAT new ObjectMapper().writer(filterProvider) is of type ObjectWriter and not of type ObjectMapper. How can I tell Jersey and Retrofit2 to use my customized ObjectWriter which uses my filters?
Since version 2.6 of Jackson it has the 'setFilterProvider' method for an ObjectMapper.
I didn't try it but the documentation has the description for this: https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/ObjectMapper.html#setFilterProvider-com.fasterxml.jackson.databind.ser.FilterProvider-. You can try i think because the description fits for your case.
I built a test service with Jersey 2.7 and Jackson 2.9.5. it works fine but you have to know some tricks to run it.
In pom.xml add Jersey and Jackson:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<properties>
<jersey.version>2.7</jersey.version>
<jackson.version>2.9.5</jackson.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
You have to define this dependence:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
</dependency>
it's mandatory.
In web.xml you have to make the ref to configuration of your service:
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>org.glassfish.jersey.server.ResourceConfig</param-name>
<param-value>com.home.MyApplication</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
MyApplication.java:
package com.home;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.ApplicationPath;
#ApplicationPath("/webapi")
public class MyApplication extends ResourceConfig {
public MyApplication() {
register(ObjectMapperProvider.class);
register(JacksonFeature.class);
register(MyResource.class);
}
}
With a custom ObjectMapperProvider you have to register a JacksonFeature.class because without it Jersey doesn't use the custom ObjectMapperProvider.
ObjectMapperProvider.java:
package com.home;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
#Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper>{
final ObjectMapper defaultObjectMapper;
public ObjectMapperProvider() {
defaultObjectMapper = createDefaultMapper();
}
#Override
public ObjectMapper getContext(Class<?> type) {return defaultObjectMapper;}
public static ObjectMapper createDefaultMapper() {
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setFilters(new SimpleFilterProvider().addFilter("dataFilter", SimpleBeanPropertyFilter.serializeAllExcept("region", "city")));
return mapper;
}
}
To define a filter use the 'setFilters' methods. This method is deprecated but the Jersey's library which called 'jersey-hk2' doesn't know the new method 'setFilterProvider' and throws an exception. With the old method everything works fine.
A business object with #JsonFilter:
#JsonFilter("dataFilter")
public class SimpleData {
#JsonProperty("name")
String firstName;
#JsonProperty("secondName")
String lastName;
#JsonProperty("country")
String country;
#JsonProperty("region")
String region;
#JsonProperty("city")
String city;
#JsonProperty("genre")
String genre;
public SimpleData() {
this.firstName = "Bryan";
this.lastName = "Adams";
this.country = "Canada";
this.region = "Ontario";
this.city = "Kingston";
this.genre = "Rock";
}
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 getCountry() { return country; }
public void setCountry(String country) { this.country = country; }
public String getRegion() { return region; }
public void setRegion(String region) { this.region = region; }
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
public String getGenre() { return genre; }
public void setGenre(String genre) { this.genre = genre; }
}
MyResource.java:
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.APPLICATION_JSON)
public SimpleData getIt() {
return new SimpleData();
}
}
A filtered result:

Maven pom.xml Spring Boot does not exist

I'm new on java world.I have this error "package org.springframework.boot does not exist" on my SpringApplication Runner class.But i added Spring Boot dependency to pom.xml
I do not understand why i got this error.
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
UserDao
#Repository
public class UsersDao {
#PersistenceContext
private EntityManager entityManager;
public void save(Users users){
entityManager.persist(users);
}
}
UserDTO
public class UsersDto {
private Integer id;
private String name;
private String surname;
private String username;
private Boolean isSuperUser;
private String email;
private String password;
private Date created_at;
private Date updated_at;
public UsersDto(){
}
public UsersDto(Users users){
this.id = users.getId();
this.name = users.getName();
this.surname = users.getSurname();
this.email = users.getEmail();
this.isSuperUser = users.getSuperUser();
this.username = users.getUsername();
this.password = users.getPassword();
}//AND GETTER&SETTER
UserResources
#Component
#Path("/users")
public class UsersResources {
#Autowired
UsersService usersService;
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response saveCity(UsersDto usersDto){
Users users;
try{
users = usersService.saveUsers(usersDto);
}catch (Exception e){
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.ok(users).build();
}
}
And UserServices
#Service
public class UsersService {
#Autowired
private UsersDao usersDao;
#Transactional
public Users saveUsers(UsersDto usersDto){
Users users = new Users();
users.setName(usersDto.getName());
users.setEmail(usersDto.getEmail());
users.setSuperUser(usersDto.getSuperUser());
users.setSurname(usersDto.getSurname());
users.setPassword(usersDto.getPassword());
usersDao.save(users);
return users;
}
}
User model
#Entity
#Table(name="users")
public class Users implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private Integer id;
#Column(name="name")
private String name;
#Column(name="surname")
private String surname;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
#Column(name="is_super_user")
private Boolean isSuperUser;
#Column(name="email")
private String email;
#Column(name="created_at")
private Date created_at;
#Column(name="updated_at")
private Date updated_at;
#PrePersist
protected void onCreate() {
created_at = new Date();
}
#PreUpdate
protected void onUpdate() {
updated_at = new Date();
}
Where is my fault?How can i fix it?And I want to ask similar question.Sometimes we got some errors but i can't find it.So we understand this error's reason is pom.xml dependency conflicts.But no error on maven.We are tired because of incompatible dependency.Has it any solution of prevent dependency conflicts?(like maven dependency validator)
For using spring boot a easier way it's to create a Spring Boot project using Spring Initiliazr https://start.spring.io/. You can create from here a maven project that has the Spring Boot or more other dependencies alredeay patched in.
If you are just starting why don't you generate the project using https://start.spring.io/.
You added core Spring dependencies but not a single Spring Boot dependency. You only have a Spring Boot BOM and parent which only manage dependencies with <dependencyManagement>. You can inspect your dependencies by running mvn dependency:tree.
If you use Intellij Idea, you can resolve this problem in such way
Right-click on the folder of your project.
Choose "Add framework support".
Find "Maven" and set the checkbox.
After that, Intellij starts to download all dependencies.

Use JPA Spring boot with SQL Server

I want to use JPA in Spring boot with SQL Server by STS
This is my table:
MAVEN
<dependencies>
<dependency>
<groupId>com.hynnet</groupId>
<artifactId>sqljdbc-chs</artifactId>
<version>4.0.2206.100</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.properties
spring.datasource.driver-class- name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=quanlybanhang
spring.datasource.username=sa
spring.datasource.password=1
spring.jpa.hibernate.ddl-auto=create
spring.datasource.initialize=true
spring.jpa.database=SQL_SERVER
Model.Account.class
#Entity
#Table(name="taikhoan",uniqueConstraints=#UniqueConstraint(columnNames = { "tendangnhap" }) )
public class Account {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#NotNull
private String tendangnhap;
#NotNull
private String matkhau;
public Account(String tendangnhap, String matkhau) {
super();
this.tendangnhap = tendangnhap;
this.matkhau = matkhau;
}
public Account() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTendangnhap() {
return tendangnhap;
}
public void setTendangnhap(String tendangnhap) {
this.tendangnhap = tendangnhap;
}
public String getMatkhau() {
return matkhau;
}
public void setMatkhau(String matkhau) {
this.matkhau = matkhau;
}
}
interface AccountDAO
public interface AccountDAO extends JpaRepository<Account, Integer>{
}
ServiceAccount.class
#Service
public class ServerAccount {
#Autowired
AccountDAO server;
public void them(Account acc){
server.save(acc);
}
public List<Account> lietke(){
return server.findAll();
}
}
ServicesAccount.class
#Service
public class ServerAccount {
#Autowired
AccountDAO server;
Account acc=new Account("khang", "1");
public void addAccount(){
server.save(acc);
}
public List<Account> lietke(){
return server.findAll();
}
}
I called method addAccount() in Controller and this is Exception I got
"java.lang.NoClassDefFoundError: org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor"
"Caused by: java.lang.ClassNotFoundException: org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"
Please help me fix this exception. Thanks!!!
From your dependencies you missed (check you java version you use):
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>6.5.2.jre8-preview</version>
<scope>test</scope>
</dependency>
and into the application properties correct this line:
spring.datasource.driver-class- name=com.microsoft.sqlserver.jdbc.SQLServerDriver
to
spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect

Categories

Resources