Hi I could need a little help understanding how I should approach following:
Just for information I'm working with play framework 2.0 and Ebeans version ~2.7
I have a model projects and a model reports. A project can have many reports but a report can only belong to one project.
This is my Projects Model:
#Entity
#Table(name = "Projects")
public class Projects extends Model {
private static final long serialVersionUID = -3343133304437498550L;
#Id
public long id;
#NotNull
#Size(min = 1, max = 255)
public String name;
#NotNull
#Size(min = 1, max = 255)
public String description;
#Formats.DateTime(pattern = "dd/MM/yyyy")
public Date created_at = new Date();
public static Finder<Long, Projects> find = new Finder<Long, Projects>(Long.class, Projects.class);
}
And this is my Reports Model:
#Entity
#Table(name = "Reports")
public class Reports extends Model {
private static final long serialVersionUID = -6617128169471038678L;
#Id
public long id;
#Constraints.Required
public String description;
#Formats.DateTime(pattern = "dd/MM/yyyy")
public Date created_at = new Date();
#ManyToOne
#NotNull
public Projects project;
public static Finder<Long, Reports> find = new Finder<Long, Reports>(Long.class, Reports.class);
}
The saving works without a problem I can create a Project and I can create multiple reports that point to the right projects. My question know is how would I go about querying this.
When I have a project how would I get all related reports to it? I think I could figure it out as a plain SQL-Query but I'm pretty sure it should be possible with ebean.
Best regards and thank you for your time!
UPDATE:
This is how I would do it with a sql query
SELECT * FROM `Projects` LEFT JOIN `Reports` ON Projects.`id` = Reports.`id`;
I can't try it right now, but I would do something like this:
public class Reports extends Model {
...
public static List<Reports> findByProject(Projects project) {
return find.fetch("project").where().eq("project.id", project.id).findList();
}
}
Related
I am trying to integrate OptaPlanner in my project. I am working with Spring jpa, maven and mysql database.
I have implemented the dependencies on my maven file, so I can use the annotations of OptaPlanner, but I don't know how to use it. I have been reading the documentation and examples but i still don't know how to use it.
I have to assign recipes and an user to a class called FoodList. Each object of FoodList has id, 2 enums, the recipe, the user and a Date, i show:
FoodList class:
#PlanningEntity()
#Entity
public class ListaComida {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Enumerated(EnumType.STRING)
private Comida comida;
#Enumerated(EnumType.STRING)
private Plato plato;
#PlanningVariable()
#ManyToOne
private Receta receta;
#PlanningVariable()
#ManyToOne
private Usuario usuario;
#Column(nullable = false)
private LocalDate fecha;
...
}
#PlanningSolution // OptaPlanner annotation
#TypeDef(defaultForType = HardSoftScore.class, typeClass = HardSoftScoreHibernateType.class) // Hibernate annotation
public class ListaComidaSolution {
#Columns(columns = {#Column(name = "hardScore"), #Column(name = "softScore")})
private HardSoftScore score;
#PlanningScore
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
}
<!-- Score configuration -->
<scoreDirectorFactory>
<easyScoreCalculatorClass>src/main/java/es.uca.AutomaticFoodList/GenerarComidaEasyScoreCalculator</easyScoreCalculatorClass>
<!--<scoreDrl>org/optaplanner/examples/cloudbalancing/solver/cloudBalancingScoreRules.drl</scoreDrl>-->
</scoreDirectorFactory>
<!-- Optimization algorithms configuration -->
<termination>
<secondsSpentLimit>30</secondsSpentLimit>
</termination>
public class GenerarComidaEasyScoreCalculator implements EasyScoreCalculator<ListaComidaSolution> {
public HardSoftScore calculateScore(ListaComidaSolution listaComidaSolution){
int hardScore = 0, softScore = 0;
return HardSoftScore.of(hardScore, softScore);
}
}
This class is not implemented, but I think I have to do it.
public static void generarListaComida(){
//SolverFactory<CloudBalance> solverFactory = SolverFactory.createFromXmlResource(
// "org/optaplanner/examples/cloudbalancing/solver/cloudBalancingSolverConfig.xml");
//Solver<CloudBalance> solver = solverFactory.buildSolver();
// Load a problem with 400 computers and 1200 processes
//CloudBalance unsolvedCloudBalance = new CloudBalancingGenerator().createCloudBalance(400, 1200);
// Solve the problem
//CloudBalance solvedCloudBalance = solver.solve(unsolvedCloudBalance);
// Display the result
//System.out.println("\nSolved cloudBalance with 400 computers and 1200 processes:\n"
// + toDisplayString(solvedCloudBalance));
}
Is this all classes and files I need to implement this in my project?, or I have to implement more classes?
On https://www.optaplanner.org/ you can download an executable demo. However it is not just an executable demo but also contains the source code of the examples ( in examples/source folder). There you can see how optaplanner is used in the example applications, and you can do the same in your application.
A good starting point is also https://docs.optaplanner.org/7.36.0.Final/optaplanner-docs/html_single/index.html#plannerConfiguration chapter 4 ff.
I am currently working with IntelliJ as my IDE and the project I am working on has a composite primary key for one of the database tables.
The table is named Measurements and has its fields laid out with one being MeasurementID as #EmbeddedID. Now IntelliJ shows me an error for the two fields which make up the MeasurementID, as the datasource I have linked does not have a separate table for those IDs. How do I tell IntelliJ inspections to refer to the other table for the named columns?
public class BaseMeasurement {
#EmbeddedId
private MeasurementId measurementId;
#Column(name = "power")
private int power;
...
}
#Embeddable
public class MeasurementId implements Serializable {
static final long serialVersionUID = 1L;
#Basic(optional = false)
#Column(name = "project_id")
private int projectId;
#Basic(optional = false)
#Column(name = "timestamp")
#Convert(converter = ZonedDateTimeConverter.class)
private ZonedDateTime timestamp;
...
}
Currently both "project_id" and "timestamp" are highlighted and marked as errors. I would like to solve those - meaning having the possibility to refer / link to the right table, where it can find those columns.
I want to create simply page where the vaadin's grid will be displayed with data from database. Unfortunately I didnt find any solution in documentation or movies... So, I have my JPA class:
#Entity
#Table
public class Movie {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column
private String movieName;
#Column
private String description;
public Movie(){}
public Movie(String movieName, String description) {
this.movieName = movieName;
this.description = description;
}
With all getters and setters. And now I want to create GUI:
#Route("show-movies")
public class MovieGUI extends VerticalLayout{}
And I tried everything: Grid < Movie>,initializeGrid, but nothing works. I just want to in simple way add 3 columns(name,desc and action) and display data from my db and button to create action. Does anyone know how to solve this problem?
Something along these lines:
#Route("show-movies")
public class MovieGUI extends VerticalLayout{
MovieGUI(MovieRepository repo) {
Grid<Movie> movieGrid = new Grid<>();
movieGrid.setItems(repo.findAll());
movieGrid.addColumn(Movie::getName).setHeader("Name");
movieGrid.addColumn(Movie::getDescription).setHeader("Description");
movieGrid.addComponentColumn(movie -> new NativeButton("Action", click-> doSomething(movie)).setHeader("");
add(movieGrid);
}
}
Check out the demo sources here for more examples: https://vaadin.com/components/vaadin-grid/java-examples
This is my first Java Spring project ever. I'm using PostgreSQL to store a WorkedDay entity as follows:
#Entity
#Table
public class WorkedDay {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column
#JsonFormat(pattern = "yyyy-MM-dd")
private Date weekDay;
#Column
private Long employeeId;
#ManyToOne
#PrimaryKeyJoinColumn(name = "employeeId", referencedColumnName = "id")
private Employee employee;
#OneToMany
private List<WorkedHours> workedHours = new ArrayList<>();
}
All "WorkedDays" are stored in a PostgreSQL table using a WorkedDayRepository class that extends CrudRepository. I'm also creating a report service which should return a list of WorkedDays in a given month.
public class WorkedDayRepositoryImpl implements WorkedDayRepositoryCustom {
public List<WorkedDay> getReportByMonthValue(int monthValue) {
//service code implementation here
}
}
I'm currently facing problems creating this custom query, since I need to retrieve from the table all Date weekDay attributes with a specific month, passed as argument.
I'm inexperienced with Spring JPA. Is there a better(or simpler) way to do this? I tried to use Specifications and Querydsl but failed.
This should work
#Repository
public interface WorkedDayRepository extends CrudRepository<WorkedDay> {
List<WorkedDay> findByWeekDay_Month(int month)
}
You could try #Query in combination with the MONTH Function.
#Repository
public interface WorkedDayRepository extends CrudRepository<WorkedDay> {
#Query("select w from WorkedDay w where MONTH(w.weekDay) = ?1")
List<WorkedDay> findByWeekDay(int month)
}
Keep in mind that not all databases might support MONTH(). Otherwise you could work with SUBSTRING(w.weekDay,6,7)
So I have really been struggling to figure this out but there doesn't seem to be good documentation on how to do this. I have an entity RepairMan with a list of Skill entities. I need a query that can return a List<RepairMan> whose list of skills contain all the skill id's. Here is what the entities look like:
#Entity
#Table(name = "REPAIRMAN")
public class RepairMan implements Serializable
{
private static final long serialVersionUID = 8151638047721448259L;
#SequenceGenerator(name="REPAIRMAN_SEQ", sequenceName="REPAIRMAN_SEQ", allocationSize=1, initialValue=100)
#Id #GeneratedValue(generator="REPAIRMAN_SEQ")
private Long id;
#OneToMany
#JoinTable(name="REPAIRMAN_SKILLS", joinColumns=#JoinColumn(name="REPAIRMAN_ID"), inverseJoinColumns=#JoinColumn(name="SKILL_ID"))
private List<Skill> skills;
....
}
#Entity
#Table(name = "SKILL")
public abstract class Skill implements Serializable
{
private static final long serialVersionUID = -5272849377636005084L;
#SequenceGenerator(name="SKILL_SEQ_GEN", sequenceName="SKILL_SEQ", allocationSize=1, initialValue=100)
#Id
#GeneratedValue(generator="SKILL_SEQ_GEN", strategy=GenerationType.SEQUENCE)
private Long id;
#Column(name="NAME")
private String name;
#Column(name="DESCRIPTION")
private String description;
...
}
And here's the desired signature and what I have been able to work out in my mind:
public class RepairManRepositoryImpl extends QueryDslRepositorySupport implements RepairManRepositoryCustom
{
public CompanyInspectorRepositoryImpl()
{
super(RepairMan.class);
}
#Override
public List<RepairMan> getRepairMenByRequiredSkills(List<Long> skillIds)
{
PathBuilder<RepairMan> repairManPath = new PathBuilder<>(RepairMan.class, "repairman");
PathBuilder repairManSkillsPath = repairManPath.get("skills"); // probably wrong
BooleanBuilder hasAllSkills = new BooleanBuilder();
for (Long skillId : skillIds)
{
hasAllSkills.and(repairManSkillsPath.getNumber("id", Long.class).eq(skillId));
}
JPAQuery query = new JPAQuery(getEntityManager())
.from(repairManPath)
//need to join the repairManSkills somehow
.where(hasAllSkills);
return query.list(repairManPath);
}
}
I know this doesn't exactly work, plus I understand it would be easier to use the Qclasses but for compatibility reasons I can't do Qclasses.