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.
Related
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.
None of these solutions helped here: Spring mockMvc doesn't consider validation in my test. Added all of these dependencies, nothing helps.
I use Spring Boot 2.1.2, pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.springtestdbunit</groupId>
<artifactId>spring-test-dbunit</artifactId>
<version>1.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.5.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-matchers</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
I use standard hibernate validation '#NotNull':
#Entity
#Table(name="employee")
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Employee {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
#NotNull(message = "Please provide name")
#Column(name = "name")
private String name;
#Column(name = "role")
private String role;
public Employee() {}
public Employee(String name, String role) {
this.name = name;
this.role = role;
}
}
#RestController
#RequestMapping(EmployeeController.PATH)
public class EmployeeController {
public final static String PATH = "/employees";
#Autowired
private EmployeeService service;
#PostMapping("")
public Employee newEmployee(#RequestBody #Valid Employee newEmployee) {
return service.save(newEmployee);
}
}
#Service
public class EmployeeService {
#Autowired
private EmployeeRepository repository;
public Employee save(Employee entity) {
return getRepository().save(entity);
}
}
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
Then I test my controller:
#RunWith(SpringRunner.class)
#SpringBootTest
#Transactional
#DatabaseSetup("/employee.xml")
#TestExecutionListeners({
TransactionalTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DbUnitTestExecutionListener.class
})
public class EmployeeControllerWebApplicationTest {
#Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private static String employeeRouteWithParam = EmployeeController.PATH + "/{id}";
#Before
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
}
#Test
public void create_WithoutName_ShouldThrowException() throws Exception {
String role = "admin";
Employee expectedEmployee = new Employee(null, role);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(expectedEmployee);
ResultActions resultActions = this.mockMvc.perform(post(PATH)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(json))
.andDo(print());
String contentAsString = resultActions.andReturn().getResponse().getContentAsString();
System.out.println("content: " + contentAsString); // empty body
resultActions
.andExpect(status().isBadRequest())
.andExpect(jsonPath("error").exists()) // not exist!!!
.andExpect(jsonPath("timestamp").exists()); // not exist!!!
}
}
employee.xml:
<dataset>
<Employee id="1" name="John" role="admin"/>
<Employee id="2" name="Mike" role="user"/>
</dataset>
I can not understand why it does not work when I test through #MockMvc. What am i doing wrong? Status is correct, but there is no error content, empty response
But validation works if tested on a really running application, then everything works.
error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping. Cannot map 'searchController' method
public java.lang.String softuniBlog.controller.SearchController.search(java.lang.String,org.springframework.ui.Model)
to {[/search]}: There is already 'searchController' bean method
public java.lang.String softuniBlog.controller.SearchController.index() mapped.
**I`m trying to build search engine for my blog and have 3 questions.
1) Why In application properties last 3 rows are "can not resolve"
2) How can I fix the error I have, app is working but when try url /search?q=someText it trows exception:
[Handler dispatch failed; nested exception is java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionDelegatorBaseImpl.(Lorg/hibernate/engine/spi/SessionImplementor;)V] with root cause
java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionDelegatorBaseImpl.(Lorg/hibernate/engine/spi/SessionImplementor;)V
3) How can take search query from input form instead from url
please check the code:
search input box
<div id="wrap">
<form action="" autocomplete="on">
<input id="search" name="search" type="text" placeholder="What're we looking for ?"></input>
<input id="search_submit" value="Rechercher" type="submit"></input>
</form>
</div>
Article controller
package softuniBlog.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import softuniBlog.bindingModel.ArticleBindingModel;
import softuniBlog.entity.Article;
import softuniBlog.entity.User;
import softuniBlog.repository.ArticleRepository;
import softuniBlog.repository.UserRepository;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
#Controller
public class ArticleConstroller {
#Autowired
private ArticleRepository articleRepository;
#Autowired
private UserRepository userRepository;
#GetMapping("/article/create")
#PreAuthorize("isAuthenticated()")
public String create(Model model){
model.addAttribute("view", "/article/create");
return "base-layout";
}
#PostMapping("/article/create")
#PreAuthorize("isAuthenticated()")
public String createProcess(ArticleBindingModel articleBindingModel){
UserDetails user = (UserDetails) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();
User userEntity = this.userRepository.findByEmail(user.getUsername());
String databasePathImage = null;
String[] allowedContentTypes = {
"image/png",
"image/jpg",
"image/jpeg"
};
boolean isContentTypeAllowed =
Arrays.asList(allowedContentTypes)
.contains(articleBindingModel.getImage().getContentType());
if(isContentTypeAllowed){
String imagesPath = "\\src\\main\\resources\\static\\img\\";
String imagePathRoot = System.getProperty("user.dir");
String imageSaveDirectory = imagePathRoot + imagesPath;
String fileName = articleBindingModel.getImage().getOriginalFilename();
String savePath = imageSaveDirectory + fileName;
File imageFile = new File(savePath);
try {
articleBindingModel.getImage().transferTo(imageFile);
databasePathImage = "/img/" + fileName;
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Article articleEntity = new Article(
articleBindingModel.getTitle(),
articleBindingModel.getContent(),
userEntity,
databasePathImage
);
this.articleRepository.saveAndFlush(articleEntity);
return "redirect:/";
}
#GetMapping("/article/edit/{id}")
#PreAuthorize("isAuthenticated()")
public String edit(#PathVariable Integer id, Model model){
if(!this.articleRepository.exists(id)){
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
if(!this.isUserAuthorOrAdmin(article)){
return "redirect:/";
}
model.addAttribute("view", "article/edit");
model.addAttribute("article", article);
return "base-layout";
}
#GetMapping("/article/{id}")
public String details(Model model, #PathVariable Integer id) {
if(!this.articleRepository.exists(id)){
return "redirect:/";
}
if(!(SecurityContextHolder.getContext().getAuthentication()
instanceof AnonymousAuthenticationToken)){
UserDetails principal = (UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
User entityUser = this.userRepository.findByEmail(principal.getUsername());
model.addAttribute("user", entityUser);
}
Article article = this.articleRepository.findOne(id);
model.addAttribute("view", "article/details");
model.addAttribute("article", article);
return "base-layout";
}
#PostMapping("/article/edit/{id}")
#PreAuthorize("isAuthenticated()")
public String editProcess(#PathVariable Integer id, ArticleBindingModel articleBindingModel) {
if(!this.articleRepository.exists(id)){
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
if(!this.isUserAuthorOrAdmin(article)){
return "redirect:/";
}
article.setTitle(articleBindingModel.getTitle());
article.setContent(articleBindingModel.getContent());
this.articleRepository.saveAndFlush(article);
return "redirect:/article/" + article.getId();
}
#GetMapping("/article/delete/{id}")
#PreAuthorize("isAuthenticated()")
public String delete(#PathVariable Integer id, Model model){
if(!this.articleRepository.exists(id)){
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
if(!this.isUserAuthorOrAdmin(article)){
return "redirect:/";
}
model.addAttribute("article", article);
model.addAttribute("view", "article/delete");
return "base-layout";
}
#PostMapping("/article/delete/{id}")
#PreAuthorize("isAuthenticated()")
public String deleteProcess(#PathVariable Integer id) {
if(!this.articleRepository.exists(id)){
return "redirect:/";
}
Article article = this.articleRepository.findOne(id);
if(!this.isUserAuthorOrAdmin(article)){
return "redirect:/";
}
this.articleRepository.delete(article);
return "redirect:/";
}
private boolean isUserAuthorOrAdmin(Article article){
UserDetails user = (UserDetails) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();
User userEntity = this.userRepository.findByEmail(user.getUsername());
return userEntity.isAdmin() || userEntity.isAuthor(article);
}
}
Article model
import javax.validation.constraints.NotNull;
import javax.persistence.*;
import java.util.Date;
#Entity
#Indexed
#Table(name = "articles")
public class Article {
private Integer id;
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
#NotNull
private String title;
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.NO)
#NotNull
private String content;
private Date date;
private User author;
private String imagePath;
public Article(String title, String content, User author, String imagePath) {
this.title = title;
this.content = content;
this.author = author;
this.imagePath = imagePath;
this.date = new Date();
}
public Article(){
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "title", nullable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name = "content", nullable = false, columnDefinition = "text")
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Column(name = "date", nullable = true)
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#ManyToOne()
#JoinColumn(nullable = false, name = "authorId")
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
#Transient
public String getSummary(){
return this.getContent().substring(0, this.getContent().length()/2) + "...";
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
Application properties
# Database connection with the given database name
spring.datasource.url = jdbc:mysql://localhost:3306/javablog
# Username and password
spring.datasource.username = root
spring.datasource.password =
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
# Using "create" will delete and recreate the tables every time the project is started
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming.strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.search.default.directory_provider = filesystem
# Using the filesystem DirectoryProvider you also have to specify the default
# base directory for all indexes (make sure that the application have write
# permissions on such directory)
spring.jpa.properties.hibernate.search.default.indexBase = ../java/softuniBlog/lucene/indexes
#Turn off Thymeleaf cache
spring.thymeleaf.cache = false
POM XML
<?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>softuni.blog</groupId>
<artifactId>blog</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Blog</name>
<description>Blog Project from the Software Technologies Course</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</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.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.7.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-infinispan</artifactId>
<version>5.7.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-elasticsearch</artifactId>
<version>5.7.0.Final</version>
</dependency>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-directory-provider</artifactId>
<version>8.2.4.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.0.Alpha2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>`enter code here`
</project>
I honestly don't understand you other questions (and you probably should ask them separately), but for question 2 I can tell you that a NoSuchMethodError is very likely to be caused by your using an incompatible version of Hibernate ORM with Hibernate Search.
To sum up:
Hibernate Search 5.7.0 and later should be used with Hibernate ORM 5.2.3 or later.
Hibernate Search 5.6.x and earlier should be used with Hibernate ORM 5.1.x or earlier.
EDIT: Your pom appears to contain a dependency to hibernate-entitymanager, and you didn't set the version for this dependency, so I suspect you're getting some older version. hibernate-entitymanager isn't required to use JPA starting with Hibernate ORM 5.2, so you should try to remove it.
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
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;
/* ... */
}