SpringBoot with JPA in IntelliJ - spring

I'm just starting with Spring, and actually I'm step by step tutorial so everything would work well, but somehow I've got problem with running spring boot after adding JPA elements.
Earlier I had problem with Database type NONE, so I manually added depedency:
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.12.1.1</version>
<scope>runtime</scope>
</dependency>
But I feel that still something is missing in pom file which looks like this:
Pom.XML
Consol output with an error looks like this:
Console output
Implementation:
1.
class Topic
2.
class TopicController
3.
class TopicRepository
4.
class: TopicService
5.
run class

You need to annotate Topic class:
package defaultpackage.topic;
/**
* Created by zales on 02.03.2017.
*/
#Entity
public class Topic {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private String id;
private String name;
private String discription;
public Topic() {
}
public Topic(String id, String name, String discription) {
super();
this.id = id;
this.name = name;
this.discription = discription;
}
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 getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
}
You can see a similar sample with Entities and Repositories in here:
https://github.com/ccoloradoc/HibernateFilePermissionSample
Also make sure all your entities are in same package(or subpackage) as your SpringBootApplication.

Related

Why the class attributes in the quarku panache example are PUBLIC instead of PRIVATE

Referring to the getting started link below
https://quarkus.io/guides/hibernate-orm-panache
The example uses a Entity class with public attributes.
class Person{
public String name;
}
and used as
person.name = "Synd";
so is it simply a lazy example (!! in official doc ? ) or it means something else.
According to the documentation, it might be related to a single difference (extending PanacheEntityBase)
If you don’t want to bother defining getters/setters for your entities, you can make them extend PanacheEntityBase and Quarkus will generate them for you. You can even extend PanacheEntity and take advantage of the default ID it provides.
Therefore they are making them Public for Quarkus to generate getters/setters for you automatically.
#Entity
public class Person extends PanacheEntity {
public String name;
public LocalDate birth;
public Status status;
public static Person findByName(String name){
return find("name", name).firstResult();
}
public static List<Person> findAlive(){
return list("status", Status.Alive);
}
public static void deleteStefs(){
delete("name", "Stef");
}
}
vs
#Entity
public class Person {
#Id #GeneratedValue private Long id;
private String name;
private LocalDate birth;
private Status status;
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getBirth() {
return birth;
}
public void setBirth(LocalDate birth) {
this.birth = birth;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}

Error creating bean with name 'clienteRestController': Unsatisfied dependency expressed through field 'clientService';

Error creating bean with name 'clienteRestController': Unsatisfied dependency expressed through field 'clientService'.
Error creating bean with name 'clientServiceImpl': Unsatisfied dependency expressed through field 'clientDao'.
Error creating bean with name 'IClienteDao': Invocation of init method failed.
nested exception is java.lang.IllegalArgumentException: Not a managed type: class java.lang.Package
I am use eclipse with spring boot project with MySQL Database, when i run the project i see this error, i see some solves in stack Overflow but not worked , can any body help, thanks
#Entity
#Table(name = "package")
public class Package implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int count;
#Column(precision=18, scale=2) /** Number (16, 2) **/
private double price;
#Column(name = "createAt")
#Temporal(TemporalType.TIMESTAMP)
private Date createAt;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
private static final long serialVersionUID = 1L;
}
Controller "ClienteRestController":
#CrossOrigin(origins = {"http://localhost:4200"})
#RestController
#RequestMapping("/apiHorsesClub")
public class ClienteRestController {
#Autowired
private IClienteService clientService;
#GetMapping("clients")
public List<Package> index()
{
return clientService.findAll();
}
}
DAO layer "clientDao":
public interface IClienteDao extends CrudRepository<Package, Long>{
}
Service layer "IClienteService" :
public interface IClienteService {
public List<Package> findAll();
}
implementation the service "ClientServiceImpl " :
#Service
public class ClientServiceImpl implements IClienteService {
#Autowired
private IClienteDao clientDao;
#Override
#Transactional(readOnly = true)
public List<Package> findAll() {
return (List<Package>) clientDao.findAll();
}
}
Thanks all, i resolved the problem.
the problem in name of the entity "Package", its reserved in Java 😂

Why is my json returned from the controller with empty fields?

I am using the debugger in IntelliJ and right before the point of returning the result, the array is perfectly fine, as you can see here
But for some reason, the response in the browser looks like this
I don't understand why the fields are invisible.
This is what my 2 models look like:
Municipality:
#Entity
public class Municipality {
#Id
#JsonIgnore
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
}
Prediction
#Entity
public class Prediction {
#Id
#JsonIgnore
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
LocalDateTime tsPredictionMade;
LocalDateTime tsPredictionFor;
float pm10;
float pm25;
#ManyToOne
#OnDelete(action = OnDeleteAction.CASCADE)
Municipality municipality;
}
And this is my controller:
#RestController
#RequestMapping("/predict")
public class PredictionController {
private MunicipalityService municipalityService;
private PredictionService predictionService;
#Autowired
public PredictionController(MunicipalityService municipalityService, PredictionService predictionService) {
this.municipalityService = municipalityService;
this.predictionService = predictionService;
}
#GetMapping
public List<Municipality> getPredictions(){
List<Municipality> result = municipalityService.getPredictions();
return result;
}
#GetMapping("/{municipality}")
public List<Prediction> getPredictionsForMunicipality(#PathVariable("municipality") String name){
List<Prediction> result = predictionService.getPredictions(name);
return result;
}
}
The rest of the app (service and persistence layer) is pretty standard.
What is the reason for this?
You will need the getters and setters for your models. The Jackson library needs it for accessing its fields when converting the models into JSON, differently from JPA when converting the resultSet into models. Here is the code:
Prediction
#Entity
public class Municipality {
#Id
#JsonIgnore
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDateTime getTsPredictionMade() {
return tsPredictionMade;
}
public void setTsPredictionMade(LocalDateTime tsPredictionMade) {
this.tsPredictionMade = tsPredictionMade;
}
public LocalDateTime getTsPredictionFor() {
return tsPredictionFor;
}
public void setTsPredictionFor(LocalDateTime tsPredictionFor) {
this.tsPredictionFor = tsPredictionFor;
}
public float getPm10() {
return pm10;
}
public void setPm10(float pm10) {
this.pm10 = pm10;
}
public float getPm25() {
return pm25;
}
public void setPm25(float pm25) {
this.pm25 = pm25;
}
public Municipality getMunicipality() {
return municipality;
}
public void setMunicipality(Municipality municipality) {
this.municipality = municipality;
}
}
Municipality
#Entity
public class Municipality {
#Id
#JsonIgnore
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
You need getters and setter for each field that you want to expose.
You can use #Data from lombok project to avoid boilerplate code.
https://projectlombok.org/

Spring Data JPA Redis : Cannot write custom method based query

I have configured Spring Data JPA with Redis and using RedisRepositories with provides methods like find(), findAll() etc. All these methods seem to be working just fine, but I am not able to write my custom method like.
RedisEntity findByGenderAndGrade(String gender, String grade);
RedisEntity is a simple POJO Entity class. If you want any more info, please let me know in messages.
Following is my entity:
#Data
#RedisHash("test1")
public class RedisEntity implements Serializable {
#Id
#GeneratedValue
private String id;
private String name;
private String gender;
private Integer grade;
}
Repository:
#Repository
public interface TestRepository extends JpaRepository<RedisEntity, String> {
List<RedisEntity> findAllByGender(String gender);
List<RedisEntity> findAllByGrade(Integer grade);
}
Service/Controller:
#Override
public List<RedisEntity> getById(String id) {
return testRepository.findById(id); //returns data perfectly.
}
#Override
public List<RedisEntity> getAllByGender(String gender) {
return testRepository.findAllByGender(gender); //returns []
}
#Override
public void saveEntity(RedisEntity redisEntity) {
testRepository.save(redisEntity); // saves it in redis perfectly.
}
Also,
findByGender and findAllByGender both give [], although I can see data in my redis database and save it as well.
As requested by FrançoisDupire,
#Configuration
public class RedisConfig {
#Autowired
private DeploymentProperties deploymentProperties;
private static Logger logger = LoggerFactory.getLogger(RedisConfig.class);
#Bean
JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("localhost", 6379);
redisStandaloneConfiguration.setPassword(RedisPassword.of("root"));
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
#Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}
}
Also, I had referred this article: Baeldung article on Spring data redis
As mentioned by #JoshJ and verified by myself and others,
The solution to the problem is:
Adding #Indexed annotation
to all those columns/fields which need to be used with all finds.
#Data
#RedisHash("EmployeeDetails")
public class RedisEntity {
#Id
private String employeeId;
private String firstName;
private String lastName;
#Indexed
private String gender;
#Indexed
private String grade;
}
We have the Spring Data Redis Library which provides the scope to write the custom method.Attaching Sample code.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.0.8.RELEASE</version>
</dependency>
Entity Definition
#Data
#RedisHash("EmployeeDetails")
public class RedisEntity {
#Id
private String employeeId;
private String firstName;
private String lastName;
private String gender;
private String grade;
}
Repository Definition
#Repository
public interface RedisEntityRepository extends CrudRepository<RedisEntity, String>{
List<RedisEntity> findAllByGenderAndGrade(String gender, String grade);
}
Implementation
#Component
public class RedisEntityImpl implements RedisEntityService {
#Autowired
private RedisEntityRepository redisEntityRepository;
#Override
public List<RedisEntity> getAllByGenderAndGrade(String gender, String grade) {
return redisEntityRepository.findAllByGenderAndGrade(gender,grade);
}
}
Properties
spring.cache.type = redis
spring.redis.host = localhost
spring.redis.port = 6379

how i can post json to springboot controller with #Embedded in #Embeddable class

the user entity
import javax.persistence.*;
#Entity
public class User {
#Id
#GeneratedValue
private Long id;
#Column(nullable = false)
private String name;
#Column(nullable = false)
private Integer age;
#Embedded
private Address address;
public User(){}
public User(String name, Integer age,Address address) {
this.name = name;
this.age = age;
this.address = address;
}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
and the address entity
#JsonInclude(JsonInclude.Include.NON_NULL)
#Embeddable
public class Address {
private String city;
public Address() {
}
public Address( String city) {
this.city = city;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
the controller code
#ResponseStatus(HttpStatus.CREATED)
#RequestMapping(value = "users", method = RequestMethod.POST)
public void users(#RequestBody List<User> users) {
this.userRepository.save(users);
}
when i post json data with psot man, the data is
[
{
"name":"yaohao",
"age":11,
"address":{
"city":"nantong"
}
},
{
"name":"yh",
"age":11,
"address":{
"city":"nantong"
}
}
]
the address always null
when the user entity has no #Embedded address entity,the code works fine,so how can i post json data to controller when i use #Embedded annotations
It has nothing to do with the use of #Embedded. When doing the marshaling Jackson uses Java Bean properties to set the values and as your User class is lacking a getAddress and setAddress Jackson simply ignores it because it doesn't exists.
To fix add the getter and setter for Address.
Or instead of using property access switch your mapper to use field access. See how to specify jackson to only use fields - preferably globally for more information on that.

Resources