Currently I am getting a problem with fetching mysql data for my springboot project:
There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
TestEntity.java
#Entity
public class TestEntity implements Serializable {
#Id
private int id;
private String p1;
private String p2;
private String p3;
public TestEntity() {
}
public TestEntity(int id, String p1, String p2, String p3){
this.id = id;
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getP1() {
return p1;
}
public void setP1(String p1) {
this.p1 = p1;
}
public String getP2() {
return p2;
}
public void setP2(String p2) {
this.p2 = p2;
}
public String getP3() {
return p3;
}
public void setP3(String p3) {
this.p3 = p3;
}
}
TestService.java
#Service
public class TestService {
#Autowired
private TestRepository testRepository;
public ArrayList<TestEntity> getAllTestEntities(){
ArrayList<TestEntity> list = new ArrayList();
testRepository.findAll().forEach(list::add);
return list;
}
public Optional getTestEntity(int id){
return testRepository.findById(id);
}
public void addTestEntity(TestEntity t){
testRepository.save(t);
}
public void removeTestEntity(int index){
testRepository.deleteById(index);
}
}
TestRepository.java
#Repository("mysql")
public interface TestRepository extends CrudRepository<TestEntity,Integer> {
}
TestController.java
#RestController
public class TestController {
#Autowired
private TestService testService;
#RequestMapping("/test/AllUnits")
public ArrayList<TestEntity> getAllTestUnits(){
return testService.getAllTestEntities();
}
#RequestMapping("/test/{id}")
public Optional getAllTestUnit(#PathVariable int id){
return testService.getTestEntity(id);
}
#RequestMapping(method=RequestMethod.POST,value = "/test" )
public void addTestUnit(#RequestBody TestEntity t){
testService.addTestEntity(t);
}
#RequestMapping(method=RequestMethod.DELETE,value = "/test/{id}" )
public void deleteTestUnit(#RequestBody Integer id){
testService.removeTestEntity(id);
}
#RequestMapping("/test/welcome")
public String welcome(){
return "welcome to springboot";
}
}
Edit: application.properties
cloud.aws.region.auto=true
cloud.aws.region.static=us-east-2
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://alyxdev.czcdgqfkwsnr.us-east-2.rds.amazonaws.com:3306/CryptoCurrency
spring.datasource.username=*******
spring.datasource.password=*******
I am able to get the /test/welcome mapping working so I believe my implementation of the service and controller is correct. So I am wondering if I made a mistake for accessing my database in my repository or should I use a JpaRepository instead of a CrudRepository and use an explicit query?
Edit Stack Trace:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'CryptoCurrency.test_entity' doesn't exist
In you Entity class i.e. TestEntity.java, you need to specify which table that your referring to
#Entity
#Table(name="tbl_something")
public class TestEntity implements Serializable {
And use of CrudRepository would be fine for excessing the database.
The application.properties file looks good to me.
I found the solution to the problem I was having apparently by renaming the table to all lowercase characters (test_table) in SQL and then using that table instead of Test_table Springboot was able to find that table and link map it to my entity class. I have no idea why it works this way. Maybe something to do with the Netbeans IDE I am using perhaps?
If annotate your entity class with #Table(name = "EmplyeeSalary") then JPA generates employee_salary as the table name. According to the naming convention at every uppercase found in the name, a new word will be generated with all lower case and will be separated from previous using _.
If you annotate your entity class like #Table(name = "AbcDefGhi") then JPA will look for abc_def_ghi table.
In my case it was due to a column was not added in table But in my entity class I am expecting that
Related
I am creating first-time spring rest services with Spring Data JPA.
and getting below error.
APPLICATION FAILED TO START
Description:
Field product_repo in com.example.demo.controller.AddProduct required a bean of type 'com.example.demo.repository.ProductRepositroy' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.example.demo.repository.ProductRepositroy' in your configuration.
My class and interfaces are :
Controller
#RestController
public class AddProduct {
#Autowired
private ProductRepositroy product_repo;
#GetMapping("/add")
public String addproduct() {
Product p1 = new Product();
p1.setId(1);
p1.setName("Amit");
Product p2 = new Product();
p1.setId(2);
p1.setName("Sumit");
product_repo.save(p1);
product_repo.save(p2);
return "added successfully the recod";
}
}
Entity
#Entity
public class Product {
#Id
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Repository
public interface ProductRepositroy extends CrudRepository<Product, Integer> {
}
Application Test
#SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
}
Add #Repository annotation on ProductRepositroy interface. Also instead of extending CrudRepository extend JpaRepository.
You should use #Repository in the repository to register this class in the bean.
Code should be something like this.
#Repository
public interface ProductRepositroy extends CrudRepository<Product, Integer> {
}
happy coding! :)
I have an Entity that would like to extend it by adding some fields. first of all they are not accessible to me to change directly, they are in their own jar file. here are the base entities:
#Entity
table(name="ACCOUNTDEF")
public class EtAccountDef
{
private String cNumber;
private List<EtAccount> accounts = new ArrayList();
public String getCNumber()
{
return cNumber;
}
public void setCNumber(String cNumber) {
this.cNumber = cNumber;
}
#OneToMany(fetch=FetchType.LAZY, cascade={javax.persistence.CascadeType.ALL}, mappedBy="accountDef")
public List<EtAccount> getAccounts() {
return accounts;
}
public void setAccounts(List<EtAccount> accounts) {
this.accounts = accounts;
}
}
which is the parent class and the below is child class:
#Entity
#Table(name="ACCOUNT")
public class EtAccount
{
private Double accountAmount;
private EtAccountDef accountDef;
private List<EtAccountItems> accountItems = new ArrayList();
#ManyToOne(fetch=FetchType.LAZY)
public EtAccountDef getAccountDef() {
return accountDef;
}
public void setAccountDef(EtAccountDef accountDef) {
this.accountDef = accountDef;
}
#OneToMany(fetch=FetchType.LAZY, cascade={javax.persistence.CascadeType.ALL}, mappedBy="account")
public List<EtAccountItems> getAccountItems() {
return accountItems;
}
public void setAccountItems(List<EtAccountItems> accountItems) {
this.accountItems = accountItems;
}
}
so I tried these changes to achieve my goal.
#MappedSuperclass
public abstract class OtAbstractAccount extends EtAccount {
private Double AccountCommission;
#Column(columnDefinition="decimal(15,2)")
public Double getAccountCommission() {
return accountCommission;
}
public void setAccountCommission(Double accountCommission) {
this.accountCommission = accountCommission;
}
and then extend it by this entity:
#Entity
#Table(name="ACCOUNT")
public class OtCostumAccount extends OtAbstractAccount {
}
The fields are now added to the base table(EtAccount) but
after compiling I get an error in the Weblogic that says:
Caused by: org.hibernate.AnnotationException: #OneToOne or #ManyToOne
on EtAccount.accountDef references an unknown entity: EtAccountDef
I have entered these two line in my ORM file:
<mapped-superclass class="package.OtAbstractAccount" />
<entity class="package.OtCostumAccount" />
Surprisingly when i comment
<mapped-superclass class="package.OtAbstractAccount" />
from ORM the weblogic does not rise any error but when I try to load object another error will be created that say:
Caused by: javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: ORA-00904:
"OtCostumAccount "."DTYPE": invalid identifier
I'm confused whit these error and I'll appreciate any help.
If you can not modify the parent class, then the default hibernate inheritance strategy apply: one table per class. This strategy require a discriminant column which, by default, is DTYPE. Did you try to add a discriminator column to your OtCostumAccount entity or create the DTYPE column ?
i have problem with saving data in DB.I'm new in Spring Boot. When i run my program the result of writen data is: packagename#randomcode example:com.abc.patient.Patient#6e3e681e
This is my Entity class - Patient.java
#Entity
public class Patient {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
// getter, setter, constructor, etc
}
This is my CrudRepo PatientRepository.java
public interface PatientRepository extends CrudRepository<Patient,Integer> {
}
This is my Service class PatientService.java
#Service
public class PatientService {
#Autowired
private PatientRepository patientRepository;
public void savePatient (String name) {
Patient patient = new Patient(name);
patientRepository.save(patient);
}
public Optional<Patient> showPatient(int id) {
return patientRepository.findById(id);
}
public List<Patient> showAllPatients() {
List<Patient> patients = new ArrayList<>();
patientRepository.findAll().forEach(patients::add);
return patients;
}
}
I think that problem in in the savePatient method in this line:
Patient patients = new Patient(name);
I checked the "name" parameter and it's in 100% correct String. I'm using Derby DB.
The only problem you have is how you are printing out your Patient class. Define a proper toString() or just debug yourself to see the resulting fields. There is no problem in your JPA implementation.
See this question for the details of default toString
Try:
public void savePatient(Patient patient) {
patientRepository.save(patient);
}
I've been following a lot of tutorial on how to get a list of result by referencing a specific column in the table.
I have this table.
I want to get the list of result with a plan_code "TEST123"
This is my code:
PlanRepository.java
public interface PlanCoverageRepository extends CrudRepository<PlanCoverage, Long> {
List<PlanCoverage> findAllByPlan_code(String plan_code);
}
PlanCoverageService.java
public interface PlanCoverageService {
public List<PlanCoverage> getAllPlanCoverageByPlanCode(String plan_code);
}
PlanCoverageServiceImpl.java
#Service
#Transactional
public class PlanCoverageServiceImpl implements PlanCoverageService {
#Override
public List<PlanCoverage> getAllPlanCoverageByPlanCode(String plan_code) {
return (List<PlanCoverage>) planCoverageRepository.findAllByPlan_code(plan_code);
}
}
PlanCoverageController.java
#Controller
#RequestMapping(value="/admin")
public class PlanCoverageController {
#Autowired
PlanCoverageService planCoverageService;
#RequestMapping(value="/Test/{plan_code}", method=RequestMethod.GET)
public ModelAndView test(#PathVariable String plan_code) {
ModelAndView model = new ModelAndView();
PlanCoverage planCoverage = (PlanCoverage) planCoverageService.getAllPlanCoverageByPlanCode(plan_code);
model.addObject("planCoverageForm",planCoverage);
model.setViewName("plan_coverage_form");
return model;
}
}
PlanCoverage.java
#Entity
#Table(name="plan_coverage")
public class PlanCoverage {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private long coverage_id;
#Column(name="plan_code")
private String plan_code;
#Column(name="coverage_description")
private String coverage_description;
/..getters and setters
#ManyToOne()
#JoinColumn(name="plan_code", referencedColumnName = "plan_code",insertable=false, updatable=false)
private Plan plan;
public Plan getPlan() {
return plan;
}
public void setPlan(Plan plan) {
this.plan = plan;
}
}
Please help me. I've been stuck with these for a few days and non of the tutorials seems to work on me. Thank you so much!!
You have messed up with the convention that spring boot is using to compose query methods. The case of the fields in the entity should follow the lower camel-case scheme, like so:
#Column(name="plan_code")
private String planCode;
and then the query method in PlanCoverageRepository should be:
List<PlanCoverage> findAllByPlanCode(String planCode);
i want to update/replace document using id field only, i am using mongoTemplate.save(p, collection) method but i am getting DuplicateKeyException: error code 11000 and error message 'E11000'
public class MongoDAO {
#Autowired
#Qualifier("mongoTemplate")
private MongoTemplate mongoTemplate;
private static final String PERSON_COLLECTION = "person";
public MongoTemplate getMongoTemplate() {
return mongoTemplate;
}
public void update(Object p) {
this.mongoTemplate.save(p, PERSON_COLLECTION);
}
}
This is my person DAO
public class PersonDAO{
#Autowired
MongoDAO mongoDAO;
public void updatePerson(){
//read
Person p1 = mongoDAO.readById("1234");
//update
p1.setName("David");
mongoDAO.update(p1);
}
}
Person.java class
package com.mongo.andy;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Field;
public class Person {
#Id
private String id;
#Field
private String name;
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;
}
}
I simply want to get the object from mongodb change the values and update the document based on _id
Using mongooperation.save() or mongotemplate.save() i am getting below error
com.mongodb.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: Person.person index: _id_ dup key: { : "5996f1d43b6af5c797a1cf4g" }'
at com.mongodb.operation.BaseWriteOperation.convertBulkWriteException(BaseWriteOperation.java:236)
at com.mongodb.operation.BaseWriteOperation.access$300(BaseWriteOperation.java:60)
at com.mongodb.operation.BaseWriteOperation$1.call(BaseWriteOperation.java:146)
at com.mongodb.operation.BaseWriteOperation$1.call(BaseWriteOperation.java:133)
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:230)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:221)
at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:133)
at com.mongodb.operation.BaseWriteOperation.execute(BaseWriteOperation.java:60)
at com.mongodb.Mongo.execute(Mongo.java:781)
at com.mongodb.Mongo$2.execute(Mongo.java:764)
at com.mongodb.DBCollection.executeWriteOperation(DBCollection.java:333)
at com.mongodb.DBCollection.insert(DBCollection.java:328)
at com.mongodb.DBCollection.insert(DBCollection.java:319)
at com.mongodb.DBCollection.insert(DBCollection.java:289)
at com.mongodb.DBCollection.insert(DBCollection.java:255)
at com.mongodb.DBCollection.insert(DBCollection.java:192)
at org.springframework.data.mongodb.core.MongoTemplate$9.doInCollection(MongoTemplate.java:1051)
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:479)
at org.springframework.data.mongodb.core.MongoTemplate.insertDBObject(MongoTemplate.java:1046)
at org.springframework.data.mongodb.core.MongoTemplate.doInsert(MongoTemplate.java:855)
at org.springframework.data.mongodb.core.MongoTemplate.doSaveVersioned(MongoTemplate.java:1001)
at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:985)
at com.mcmcg.dia.account.metadata.dao.MongoDAO.update(MongoDAO.java:105)
at com.mcmcg.dia.account.metadata.service.AccountOALDService.mongotestapi(AccountOALDService.java:265)
at com.mcmcg.dia.account.metadata.service.AccountOALDService$$FastClassBySpringCGLIB$$7f85f843.invoke(<generated>)
Please provide the solution and suggest if there is any other way to update/replace documents in mongodb using spring-data on the basis of id field only. I have large custom object and not interesting writing any queries for update.
I was able to do so in couchbase db using upsert(), finding similar way in mongodb.
Instead of this.mongoTemplate.save(p, PERSON_COLLECTION); try with:
public void update(Object p) {
BasicDBObject dbObject = new BasicDBObject();
mongoTemplate.getConverter().write(p, dbObject);
mongoTemplate.upsert(new Query(Criteria.where("_id").is(((Person) p).getId())),
Update.fromDBObject(dbObject, "_id"), PERSON_COLLECTION);
}
The solution is similar to how the upsert method it is implemented in MongoTemplate.