Problem: After a long research how I can serialize data from a database with two tables I have found that tutorial. But I need to get the data out of the database and I do not know how to get connect the data to the database.
I have found only non-relational samples with one table.
Question: Does someone have a sample for the DAO class to get the data for the characteristics out of the database?
JSON structure needed:
[
{
"id":1,
"name":"CNC",
"beschreibung":"Metallverarbeitung",
"characteristics":[
"id_characteristic":1,
"id_maschine":2,
"name":"size",
"description":"length of maschine",
"type":1
]
}
]
current JSON structure:
[
{
"id":1,
"name":"CNC",
"beschreibung":"Metallverarbeitung",
"characteristics":[
]
},
...
]
DAO method (until now, does not fill the characteristics Array):
#Override
public List<Maschine> list() {
String selectMaschines = "SELECT * FROM maschine";
List<Maschine> listMaschine = jdbcTemplate.query(selectMaschines, new RowMapper<Maschine>() {
#Override
public Maschine mapRow(ResultSet rs, int rowNum) throws SQLException {
Maschine aMaschine = new Maschine();
aMaschine.setId(rs.getInt("Maschine_id"));
aMaschine.setName(rs.getString("name"));
aMaschine.setBeschreibung(rs.getString("beschreibung"));
return aMaschine;
}
});
return listMaschine;
}
Table structure:
Maschine table:
maschine_id || name || description
Characteristic table:
id_characteristic || id_maschine || name || description || type
If you want to work with spring data you have to add spring data dependency to your pom.xml
then add the annotation for your entities :
#Entity
public class Maschine implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int maschine_id ;
private String name ;
private String description ;
#OneToMany(mappedBy="maschine")
private Collection<Characteristic> characteristics;
public Maschine() {
super();
// TODO Auto-generated constructor stub
}
public int getMaschine_id() {
return maschine_id;
}
public void setMaschine_id(int maschine_id) {
this.maschine_id = maschine_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
// Characteristic entity
#Entity
public class Characteristic implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id_characteristic ;
private String name;
private String description;
private String type ;
#ManyToOne
#JoinColumn(name="id_machine")
private Maschine maschine;
public int getId_characteristic() {
return id_characteristic;
}
public void setId_characteristic(int id_characteristic) {
this.id_characteristic = id_characteristic;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Maschine getMaschine() {
return maschine;
}
public void setMaschine(Maschine maschine) {
this.maschine = maschine;
}
public Characteristic() {
super();
// TODO Auto-generated constructor stub
}
}
And in your DAO package you have to create a interface that extends JPARepository for exemple :
public interface MaschineRepository extends JpaRepository<Maschine,Integer> {
}
then when you call MaschineRepository.findAll() you will get all the maschines with their Characteristics
Spring data dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
don't forget to add the database configuration in your application.properties if you work with spring boot
Related
this problem only occurs when I get the data from the database, the application is replacing the _ with . this only happens when I get the record from the database
data in database
[{"nombre": "pablo", "pais(codigo)": "52", "telefono": "", "saldo_total": "10"}, {"nombre": "pablo", "pais(codigo)": "52", "telefono": "", "saldo_total": "10"}]
entity in java code
#EnableMongoRepositories
#Document(collection = "data")
public class DataEntity extends BaseMongoEntity {
#Id
private String id;
#Field(value = "company_id")
private int companyId;
private String name;
private String url;
private List<String> variables;
private List<Object> info;
public DataEntity() {
super();
// TODO Auto-generated constructor stub
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getCompanyId() {
return companyId;
}
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public List<String> getVariables() {
return variables;
}
public void setVariables(List<String> variables) {
this.variables = variables;
}
public List<Object> getInfo() {
return info;
}
public void setInfo(List<Object> info) {
this.info = info;
}
}
query to find the record in database
public DataEntity findById(String id) {
ObjectId idO = new ObjectId(id);
Query query = new Query(Criteria.where("_id").is(idO));
return mongoTemplate.findOne(query, DataEntity.class);
}
image of data obtained in object format
only happens when the record is obtained but not when saving data in the database.
I know there are a few questions on stackoverflow regarding this problem. But I have have been spending hours trying to resolve this error without any success.
I am using the mysql database to store the values.
I keep on getting the error message from the
com.example.springboot.Recipe file.
This is springboot recipe file
package com.example.springboot;
import com.example.springboot.Recipe;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
#Entity // This tells Hibernate to make a table out of this class
public class Recipe {
public Recipe(){
}
public Recipe(Integer id, String name, String description, String type, Integer preptime, Integer cooktime, String content, Integer difficulty){
this.id = id;
this.name = name;
this.description = description;
this.type = type;
this.preptime = preptimee;
this.cooktime = cooktime;
this.content = content;
this.difficulty = difficulty;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String description;
private String type;
private Integer preptime;
private Integer cooktime;
#Column(columnDefinition = "TEXT")
private String content;
private Integer difficulty;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return name;
}
public void setTitle(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getDifficulty() {
return difficulty;
}
public void setDifficulty(Integer difficulty) {
this.difficulty = difficulty;
}
public Integer getCookingtime() {
return cooktime;
}
public void setCookingtimeime(Integer cooktime) {
this.cooktime = cooktime;
}
public Integer getPreparationtime() {
return preptime;
}
public void setPreparationtime(Integer preptime) {
this.preptime = preptime;
}
}
Main Controller:
#PutMapping("/recipes/edit/{id}")
void updateRecipe2(#PathVariable int id, #RequestBody Recipe recipe ) {
Recipe recipe_ = recipeRepository.findById(id).get();
recipe_.setTitle(recipe.getTitle());
System.out.println("sss " + recipe.getname());
System.out.println("change");
recipeRepository.save(recipe_);
}
service.ts:
updateRecipe2 (id: number, recipe: any): Observable<any > {
const url = `${this.usersUrl}/edit/${id}`;
return this.http.put(url ,recipe);
}
where the updateRecipe2 gets called:
save(): void {
const id = +this.route.snapshot.paramMap.get('name');
this.recipeService.updateRecipe2(id, this.recipes)
.subscribe(() => this.gotoUserList());
}
as soon as the user clicks save this functions saves the changes made.
I hope the code snippets that I provided are enough to help solve the problem.
Thank you in advance.
I am building a rest api with spring boot and I am using angularjs as it's frontend. I am pretty new to web-development.
You are sending a list of recipes to an api endpoint that expects a single recipe object.
Your options are:
Send only one recipe object at a time, for example:
this.recipeService.updateRecipe2(id, this.recipes[0])
OR: create a new API endpoint to accept a list of recipes, to edit them in "batch"
#PutMapping("/recipes/edit")
void updateRecipes(#RequestBody List<Recipe> recipe ) {
my Example:
Use:
#PostMapping
Code:
public void setTransacciones(List<Transacciones> transacciones) {
this.transacciones = transacciones;
}
CodeBean:
public class Transacciones {
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
private String text;
}
Post(raw):
{
"transacciones" : [ {"text" : "1"}, {"text" : "2"} ]
}
Result:
{
"transacciones": [
{
"transaccionId": 2,
"text": "1"
},
{
"transaccionId": 3,
"text": "2"
}
]
}
BINGO!!
I am using JPA to query flyway_schema_history to print a report of the executed migrations. The structure of flyway_schema_history is repeated across all the schemas in my Postgresql database. Also, I am passing the name of the schema as a parameter when I run the program.I am using Java 10.
I created this entity in JPA.
#Entity
#Table(name = "flyway_schema_history", schema="this_should_be dynamic")
public class FlywaySchemaHistoryGeneric {
#Id
#Column(name="installed_rank")
private Integer installedRank;
#Column(name="version")
private String version;
#Column(name="description")
private String description;
#Column(name="type")
private String type;
#Column(name="script")
private String script;
#Column(name="checksum")
private Integer checksum;
#Column(name="installed_by")
private String installedBy;
#Column(name="installed_on")
private Date installedOn;
#Column(name="execution_time")
private Integer executionTime;
#Column(name="success")
private Boolean success;
public Integer getInstalledRank() {
return installedRank;
}
public void setInstalledRank(Integer installedRank) {
this.installedRank = installedRank;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getScript() {
return script;
}
public void setScript(String script) {
this.script = script;
}
public Integer getChecksum() {
return checksum;
}
public void setChecksum(Integer checksum) {
this.checksum = checksum;
}
public String getInstalledBy() {
return installedBy;
}
public void setInstalledBy(String installedBy) {
this.installedBy = installedBy;
}
public Date getInstalledOn() {
return installedOn;
}
public void setInstalledOn(Date installedOn) {
this.installedOn = installedOn;
}
public Integer getExecutionTime() {
return executionTime;
}
public void setExecutionTime(Integer executionTime) {
this.executionTime = executionTime;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
}
I was trying to use FlywaySchemaHistoryGeneric.class.getAnnotation to change the value in runtime without success, but I think that it should be an easy way to do it.
How can I do to make schema from #table to be dynamic?
I guess you wont be able to modidy that in runtime because annotations are read-only. You can create one datasource for each schema and choose one of them to persist the entity based in your rules.
#Entity
public class Category {
#Id
private Long id;
private String name;
private String description;
#Load
private List<Ref<Subcategory>> subcategories = new ArrayList<Ref<Subcategory>>();
#Load
private Ref<Image> image;
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Subcategory> getSubcategories() {
List<Subcategory> scs = new ArrayList<Subcategory>();
for (Ref<Subcategory> sc : this.subcategories) {
scs.add(sc.get());
}
return scs;
}
public void setSubcategory(Subcategory subcategory) {
this.subcategories.add(Ref.create(subcategory));
}
public Image getImage() {
if(image != null) {
return image.get();
}
return null;
}
public void setImage(Image image) {
this.image = Ref.create(image);
}
}
#Entity
public class Subcategory {
#Id
private Long id;
private String name;
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class CategoryDTO {
private Long id;
#NotNull
private String name;
private String description;
private List<Subcategory> subcategories = new ArrayList<Subcategory>();
private Long imageId;
public CategoryDTO() {
}
public CategoryDTO(Category category) {
this.id = category.getId();
this.name = category.getName();
this.description = category.getDescription();
this.subcategories = category.getSubcategories();
if (category.getImage() != null) {
this.imageId = category.getImage().getId();
}
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Subcategory> getSubcategories() {
return subcategories;
}
public void setSubcategories(List<Subcategory> subcategories) {
this.subcategories = subcategories;
}
public Long getImageId() {
return imageId;
}
public void setImageId(Long imageId) {
this.imageId = imageId;
}
}
CategoryDAO
public class CategoryDAO {
private static final Logger log = Logger.getLogger(CategoryService.class.getName());
public static QueryResultIterator<Category> getCategories() {
QueryResultIterator<Category> categories = ofy().load().type(Category.class).iterator();
return categories;
}
}
public class SubcategoryDAO {
public static Subcategory createSubcategory(Long categoryId, Subcategory data) {
// save sub category
Subcategory subcategory = new Subcategory();
if (data.getName() != null) {
subcategory.setName(data.getName());
}
if (data.getDescription() != null) {
subcategory.setDescription(data.getDescription());
}
ofy().save().entity(subcategory).now();
Category category =
ofy().load().type(Category.class).id(categoryId).get();
category.setSubcategory(subcategory);
ofy().save().entity(category).now();
return subcategory;
}
}
CategoryService
#Path("/categories")
public class CategoryService {
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getCategories() {
try {
List<CategoryDTO> categories = new ArrayList<CategoryDTO>();
QueryResultIterator<Category> cats = CategoryDAO.getCategories();
while (cats.hasNext()) {
categories.add(new CategoryDTO(cats.next()));
}
Map<String, List<CategoryDTO>> map = new HashMap<String, List<CategoryDTO>>();
map.put("categories", categories);
return Helper.prepareResponse(map);
} catch (Exception e) {
LogService.getLogger().severe(e.getMessage());
throw new WebApplicationException(500);
}
}
}
Problem:-
When i hit getCategories service, it is showing unexpected behaviour.Instead of showing all the subcategories, it is showing random no of different subcategories every time.
For example say,
first i save a category "c"
then i save subcategories "sa", "sb" and "sc"
On hitting getCategry service,
Expected Behaviour -
{
"status": 200,
"categories" : [{
"name":a,
"subcategories": [
{
"name":"sa"
},
{
"name":"sb"
},
{
"name":"sc"
}
]
}]
}
Outputs i get is something like this -
{
"status": 200,
"categories" : [{
"name":a,
"subcategories": [
{
"name":"sa"
},
{
"name":"sc"
}
]
}]
}
or
{
"status": 200,
"categories" : [{
"name":a,
"subcategories": [{
"name":"sb"
}]
}]
}
To summarize this question, you're performing a query (give list of all categories) and getting back inconsistent results.
This is the system working as advertised. Read this: https://cloud.google.com/appengine/docs/java/datastore/structuring_for_strong_consistency
Eventual consistency is something that you learn to live with and work around when you need it. There is no way to force a query to be strongly consistent without changing the structure of your data - say, put it under a single entity group - but that has repercussions as well. There is no free lunch if you want a globally replicated, infinitely-scalable database.
In addition to eventual consistency, the datastore has no defined ordering behavior if you do not specify a sort order in your query. So that might add to your confusion.
Welcome to the wonderful world of eventual consistency. When I encountered something like this, using ObjectifyService.begin() instead of ObjectifyService.ofy() resolved it. Unlike ofy(), begin() gets you fresh data every time.
I want to convert the following query into HQL:
SELECT C.ID, E.DESCRIPTION as STATUS, E1.DESCRIPTION as SUBJECT
FROM CRED C
join CODE_EVN E
ON E.CODE = C.STATUS_CODE
AND E.SUBCODE = C.STATUS_SUBCODE
join CODE_EVN E1
ON E1.CODE = C.SUBJECT_CODE
AND E1.SUBCODE = C.SUBJECT_SUBCODE
I have two classes User and Codes with no mapping in between them, so how do I execute the following query in Hibernate?
I have tried out many things but nothing seems to work
These are my 2 bean classes:
User class:
#Entity
#Table(name="CRED")
public class User {
private String id;
private String STATUS_CODE;
private String STATUS_SUBCODE;
private String SUBJECT_CODE;
private String SUBJECT_SUBCODE;
#Id
#Column(name="ID")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setSTATUS_CODE(String sTATUS_CODE) {
STATUS_CODE = sTATUS_CODE;
}
public String getSTATUS_CODE() {
return STATUS_CODE;
}
public void setSTATUS_SUBCODE(String sTATUS_SUBCODE) {
STATUS_SUBCODE = sTATUS_SUBCODE;
}
public String getSTATUS_SUBCODE() {
return STATUS_SUBCODE;
}
public void setSUBJECT_CODE(String sUBJECT_CODE) {
SUBJECT_CODE = sUBJECT_CODE;
}
public String getSUBJECT_CODE() {
return SUBJECT_CODE;
}
public void setSUBJECT_SUBCODE(String sUBJECT_SUBCODE) {
SUBJECT_SUBCODE = sUBJECT_SUBCODE;
}
public String getSUBJECT_SUBCODE() {
return SUBJECT_SUBCODE;
}
}
Codes class:
#Entity
#Table(name="CODE_EVN")
public class Codes {
#Id
private String CODE;
private String SUBCODE;
private String DESCRIPTION;
public void setCODE(String cODE) {
CODE = cODE;
}
public String getCODE() {
return CODE;
}
public void setSUBCODE(String sUBCODE) {
SUBCODE = sUBCODE;
}
public String getSUBCODE() {
return SUBCODE;
}
public void setDESCRIPTION(String dESCRIPTION) {
DESCRIPTION = dESCRIPTION;
}
public String getDESCRIPTION() {
return DESCRIPTION;
}
}