Using Comparable To Compare and sort TreeSet in Descending Of JPA Entity Id
I am trying to sort my TreeSet using JPA Auto Generated Id. Here, Note is an Entity class.
@Entity
@Table(name="NOTE")
@Getter
@Setter
public class Note implements Comparable<Note> {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String note;
@ManyToOne
@JoinColumn(name = "noteDetailsId")
private NoteDetails noteDetails;
@override
public int compareTo(Note myNote) {
return myNote.getId().intValue() - this.getId().intValue();
}
}
@Entity
@Table(name="NOTE_DETAILS")
@Getter
@Setter
class NoteDetails {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "noteOperation", cascade = Cascadetype.ALL, orphanRemoval = true, fetch=fetchType.EAGER)
private Set<Note> notes = new TreeSet<>();
public void addNote(String note) {
this.notes.add(new Note().setNote("note1"));
}
}
My problem is that, I am getting JPA Ids as null in compareTo() method. Hence thowing nullPointerException. My purpose is to sort TreeSet in descending order of JPA Ids. But those Ids are coming null.
do you know?
how many words do you know
See also questions close to this topic
-
Read each name in Array list to create seperate object for
I have a file that has student names, age, and an id number. I have a student class that holds the everything above for each student object. I stored all the names, id numbers. and age separately in an array list. Now im trying to assign the info to create a student object.
public class Student { private String lName; private int idNumber; private int age; public Student() { lName = ""; idNumber = 0; age = 0; } public Student(String l, int i, int a) { lName = l; idNumber = i; age = a; } public void setName(String last) { lName = last; } public String getName() { return lName; } public void setIdNum(int num) { idNumber = num; } public int getIdNum() { return idNumber; } public void setAge(int a) { age = a; } public int getAge() { return age; } }
My Text File looks something like this: This info is stored in parallel array lists. I don't quite get how to implement this into an object to pass it into my second contractor method.
Josh 2134 19 Smith 5256 21 Rogers 9248 19 Andrew 7742 20
Here's what I've tried;
public static void main(String[] args) { String file = "studentData.txt"; Scanner reader = new Scanner(file); ArrayList<String> lastNames = lNames(file); ArrayList<Integer> idNumbers = idNum(file); ArrayList<Integer> ageList = ages(file); Scanner input = new Scanner(System.in); Student s1 = new Student(); // confused about how to implement this constructor with the textile info for (int i = 0; i<idNumbers.size(); i++) { Student user = new Student(lastNames.get(i), idNumbers.get(i), ageList.get(i)); } //user enters idNumber to display age System.out.println("Enter ID Number"); //exception handling to be added int idNum = input.nextInt(); for (int i = 0; i<idNumbers.size(); i++) { if (idNum == idNumbers.get(i)) { s1.setAge(ageList.get(i)); System.out.println(s1.getAge()); } } }
-
Using EdittextPreference for Goto search
sorry for my poor English. I want to use EditTextPreference in my bottom nav like the pic below, ![screenshot][1]
I have recycleview xml in my project with in many sub cardview layouts(which is scrollable) and I want to create item in the bottom nav which is called "Goto". When the "Goto" item is clicked i want it to pop-up like the screenshot. And when user enters a number(according to the cardviews i.e if the number of cardview is 40 user must enter 1-40) I want to search the cardview by its ID. Thank you and I hope u got it, If u have any questions let me know [1]: https://i.stack.imgur.com/grK8P.jpg
My xml format look like this. As you see in the blow since the cardviews are huge in number it is not cool to scroll all the way down that is why i need Goto item in the bottom nav to search it by its ID when the user click number in the EditTextPreference as u see in the screenshot. i.e The screenshot is not from my app
<LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> .. .. .. .. many more..
-
How to get remaining time of the day in java?
I would like to calculate the time remaining for next day 00:00:00 from the current date time.
For e.g. time difference between 2
022-05-07T05:49:41.883807900Z
and2022-05-08T00:00:00Z
Expected answer:
18:10:19
or 65419 (in seconds).How can I achieve this with efficiently using java 8?
-
Hibernate handles id assigning instead of database
I have an auto-increment PK in a table and I want hibernate to handle id assigning instead of database. As my understanding the
@GeneratedValue(strategy = GenerationType.IDENTITY)
lets the database generate a new value with each insertion operation. So do we have any different solution to handle it? -
Some table rows are not returned by hibernate native query
I'm having a big problem that a few rows of the table are not returning by the native query of hibernate (Spring Data), although if I put the same query in the database it returns. No exceptions or warnings appear in the log. My database is MySQL.
Follows the query:
@Query(value = "SELECT MID(UUID(),1,36) as unique_key, " + "TRIM(avio_sinr.num_sinr) as num_sinr, " + "avio_sinr.dat_alte_regc, " + "avio_sinr.dat_cria_sinr, " + "avio_sinr.vlr_limi_inde, " + "avio_sinr.vlr_pgto_sinr, " + "TRIM(avio_sinr.cod_apol_prco) as cod_apol_prco, " + "ctto_usua_prco.nom_emai_usua_prco, " + "ctto_usua_prco.num_cell_usua_prco, " + "ctto_usua_prco.cod_ddi_tel_usua_prco, " + "ctto_usua_prco.cod_ddd_tel_usua_prco, " + "ctto_usua_prco.cod_ddi_cell_usua_prco, " + "ctto_usua_prco.cod_ddd_cell_usua_prco, " + "dado_pgto.bco, " + "dado_pgto.cod_tipo_cont_bace, " + "dado_pgto.agencia, " + "dado_pgto.num_cont_clie, " + "dado_pgto.num_digt_verf, " + "ende_prco.id_cep_logr, " + "ende_prco.nom_bair_usua_prco, " + "ende_prco.nom_cida_usua_prco, " + "ende_prco.nom_logr_usua_prco, " + "ende_prco.num_ende_usua_prco, " + "ende_prco.sg_uf, " + "ende_prco.txt_cmpl_usua_prco, " + "even_ocro.cod_ramo_sega, " + "even_ocro.nom_even_infd, " + "gara_disi.cod_gara_sinr, " + "gara_disi.cod_cobt, " + "gara_disi.cod_prod_segu, " + "gara_disi.des_gara_sinr, " + "gara_disi.nom_gara_sinr, " + "prco_abet_sinr.num_prco_sinr, " + "prco_abet_sinr.dat_hor_abet_prco, " + "prco_abet_sinr.dat_ocor_sinr, " + "prco_abet_sinr.hor_ocor_sinr, " + "prco_abet_sinr.num_funl_cola_cogl, " + "prco_abet_sinr.num_funl_rspl_regc, " + "prco_abet_sinr.txt_ocor_sinr, " + "situ_prco.nom_situ_prco, " + "situ_sinr.nom_situ_sinr, " + "tipo_rela_solt_benf.cod_tipo_rela, " + "tipo_rela_solt_benf.des_tipo_rela, " + "tipo_rela_solt_benf.nom_tipo_rela, " + "usua_prco.cod_sexo, " + "usua_prco.cod_tipo_pess, " + "usua_prco.nom_cpto_usua_prco, " + "usua_prco.num_cpf_cnpj_usua_prco, " + "segu_prot_prec_clie.vlr_ofrt_clie, " + "decs_avio_sinr.dat_hor_decs, " + "decs_avio_sinr.txt_decs_anai " + "FROM prco_abet_sinr prco_abet_sinr " + "LEFT JOIN avio_sinr avio_sinr ON (prco_abet_sinr.num_prco_sinr = avio_sinr.num_prco_sinr) " + "LEFT JOIN situ_sinr situ_sinr ON (avio_sinr.cod_situ_sinr = situ_sinr.cod_situ_sinr) " + "LEFT JOIN situ_prco situ_prco ON (prco_abet_sinr.cod_situ_prco = situ_prco.cod_situ_prco) " + "LEFT JOIN usua_prco usua_prco ON (prco_abet_sinr.cod_usua_prco = usua_prco.cod_usua_prco) " + "LEFT JOIN ctto_usua_prco ctto_usua_prco ON (usua_prco.cod_usua_prco = ctto_usua_prco.cod_usua_prco) " + "LEFT JOIN dado_pgto dado_pgto ON (prco_abet_sinr.num_prco_sinr = dado_pgto.num_prco_sinr) " + "LEFT JOIN ende_prco ende_prco ON (usua_prco.cod_usua_prco = ende_prco.cod_usua_prco) " + "LEFT JOIN even_ocro even_ocro ON (prco_abet_sinr.num_prco_sinr = even_ocro.num_prco_sinr) " + "LEFT JOIN gara_disi gara_disi ON (avio_sinr.cod_gara_sinr = gara_disi.cod_gara_sinr) " + "LEFT JOIN tipo_rela_solt_benf tipo_rela_solt_benf ON (usua_prco.cod_tipo_rela = tipo_rela_solt_benf.cod_tipo_rela) " + "LEFT JOIN segu_prot_prec_clie segu_prot_prec_clie ON (prco_abet_sinr.num_prco_sinr = segu_prot_prec_clie.num_prco_sinr) " + "LEFT JOIN decs_avio_sinr decs_avio_sinr ON (avio_sinr.num_sinr = decs_avio_sinr.num_sinr) " + "ORDER BY avio_sinr.num_sinr AND avio_sinr.dat_alte_regc DESC " + "LIMIT :offset, :limit ", nativeQuery = true) List<MovimentacaoSinistroEntity> findByProtocoloSinistroPaginacao(Long limit, Long offset);
Follows the class:
@Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder public class MovSiEntity { @EmbeddedId private MovPK movSiPK; @Column(name = "num_sinr") private String numberSi; @Column(name = "cod_gara_sinr") private Integer codeWarrantSi; @Column(name = "dat_alte_regc") private LocalDate dateAlteracaoRegistroSi; @Column(name = "dat_cria_sinr") private LocalDateTime dateCriacaoSi; @Column(name = "vlr_limi_inde") private BigDecimal valueLimiteIndenizacaoSi; @Column(name = "vlr_pgto_sinr") private BigDecimal valuePagamentoSi; @Column(name = "dat_hor_abet_prco") private LocalDateTime dateOpenProtocol; @Column(name = "dat_ocor_sinr") private LocalDate dateOcorrenciaSi; @Column(name = "hor_ocor_sinr") private Time hourOcorrenciaSi; @Column(name = "vlr_ofrt_clie") private BigDecimal valueOfferClient; @Column(name = "dat_hor_decs") private LocalDateTime dateHourdecision; @Column(name = "nom_emai_usua_prco") private String emailUserProtocol; @Column(name = "cod_ddi_tel_usua_prco") private Short codeDdiTelUserProtocol; @Column(name = "cod_ddd_tel_usua_prco") private Short codeDddTelUserProtocol; @Column(name = "cod_ddi_cell_usua_prco") private Short codeDdiCelUserProtocol; @Column(name = "cod_ddd_cell_usua_prco") private Short codeDddCelUserProtocol; @Column(name = "bco") private String codeBanco; @Column(name = "cod_tipo_cont_bace") private String codeTipoAccountBacen; @Column(name = "agencia") private String agencia; @Column(name = "num_cont_clie") private String numberAccountClient; @Column(name = "num_digt_verf") private String numberDigitoVerify; @Column(name = "id_cep_logr") private String cepplace; @Column(name = "nom_bair_usua_prco") private String bairroUserProtocol; @Column(name = "nom_cida_usua_prco") private String cidadeUserProtocol; @Column(name = "nom_logr_usua_prco") private String placeUserProtocol; @Column(name = "sg_uf") private String siglaUnidadeFederacao; @Column(name = "txt_cmpl_usua_prco") private String complementoplaceUserProtocol; @Column(name = "nom_even_infd") private String nomeEventoInformado; @Column(name = "des_gara_sinr") private String descWarrant; @Column(name = "nom_gara_sinr") private String nomeWarrant; @Column(name = "num_funl_cola_cogl") private String funcionalColaboradorConglomerado; @Column(name = "num_funl_rspl_regc") private String funcionalResponsavelRegulacao; @Column(name = "txt_ocor_sinr") private String textoOcorrenciaSi; @Column(name = "des_tipo_rela") private String descriptionTipoRelacao; @Column(name = "nom_tipo_rela") private String nomeTipoRelacao; @Column(name = "cod_sexo") private String codeSexo; @Column(name = "cod_tipo_pess") private String codeTipoPessoa; @Column(name = "nom_cpto_usua_prco") private String nomeCompletoUserProtocol; @Column(name = "num_cpf_cnpj_usua_prco") private String numberCpfCnpjUserProtocol; @Column(name = "num_cell_usua_prco") private Integer numberCelularUserProtocol; @Column(name = "num_ende_usua_prco") private Integer numberEnderecoUserProtocol; @Column(name = "cod_ramo_sega") private Integer codeRamoSeguradora; @Column(name = "cod_tipo_rela") private Integer codeTipoRelacao; @Column(name = "cod_cobt") private Integer codeCobertura; @Column(name = "cod_prod_segu") private Integer codeProdutoSeguro; @Column(name = "nom_situ_prco") private String nomeSituacaoProtocol; @Column(name = "nom_situ_sinr") private String nomeSituacaoSi; @Column(name = "txt_decs_anai") private String decisionAnalista; }
follows the Embeddable class:
@Embeddable @Getter @Setter @Builder @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor public class MovSiPK implements Serializable { @Column(name = "unique_key") private String uniqueKey; @Column(name = "num_prco_sinr", nullable = false) private String numberProtocolSi; @Column(name = "cod_apol_prco") private String codeApoliceProtocol; }
-
Spring boot mapsId
Hi I using spring boot jpa and I need to use mapsid. There are not so much information about that and I wonder if anyone can help me understand how to use maybe link a simple code example where its 2 table that joins 1 table (oneToOne)
-
Select only a set to improve perfomance
I search to know if a user have an active subscription
@Query("select case when count(u) > 0 then true else false end from User u where u.id=:userId and current_date < u.subscriptionEndDate") boolean userActiveSubscription(Long userId);
subscriptionEndDate use a localdate
Probably user object is queried, is there a way to limit data retrived to return true or false
-
JPA cascading delete fails with custom delete method
I ran into an error with custom delete method in spring data jpa. Basically there's a bag which contains items, and when deleting the bag, all the items in it should be deleted.
Here're the entities:
@Entity @Table(name = "bag") public class Bag { @Id private Long id; @Column("uid") private Long uid; @Column("name") private String name; @OneToMany(mappedBy = "bag", cascade = CascadeType.ALL, orphanRemoval = true) private List<Item> items; } @Entity @Table(name = "item") public class Item { @Id private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "bid", referencedColumnName = "id") private Bag bag; }
and the repository:
@Repository public interface BagRepository extends JpaRepository<Bag, Long> { Bag findByUidAndName(Long uid, String name); @Transactional @Modifying @Query(value = "DELETE FROM `bag` WHERE `uid` = :uid AND `name` = :name", nativeQuery = true) void deleteByUidAndName(@Param("uid") Long uid, @Param("name") String name); }
When I call
bagRepository.deleteByUidAndName(uid, name)
, I get an Exception from hibernate relating to foreign key constraint. Settingspring.jpa.show-sql=true
shows it does not try to delete the items first before deleting the bag.However, if I call
Bag bag = bagRepository.findByUidAndName(uid, name)
and thenbagRepository.deleteById(bag.getId())
everything is fine.I'd like to know what's wrong about customizing this delete method and how to fix it.
-
How to compare values in an array using compareTo method by implementing comparable interface?
I have class Person has private variables that hold the first and last name, age, height. I have another class Student that extends Person by adding a private variable grade (values 1-12). I need to have the constructor and getter/setter methods. I need to Make Student class implement the Comparable interface with the compareTo method ordering Student objects by grade first, then last name, then first name. But I am getting error while I am using compareTo method in student class. Error is > operator is not used with the int[], int[]. Actually, the questions says that values of arrays are between 1 to 12 . I am not sure, is it an array or a single value. If its a single value, is there any need to add setter for the grade variable. Can someone give me a clarity about this thing.
public class Student extends Person implements Comparable<Student>{ private int grade[]; public Student(String firstName, String lastName, int age, int height, int[] grade) { super(firstName, lastName, age, height); this.grade = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; } public int[] getGrade() { return grade; } public void setGrade(int[] grade) { this.grade = grade; } @Override public int compareTo(Student o) { if(this.getGrade() > o.getGrade()){ return 1; } else if(this.getGrade() < o.getGrade() < 0){ return -1; } else{ if(this.getLastName().compareTo(o.getLastName()) > 0){ return 1; } else if(this.getLastName().compareTo(o.getLastName()) < 0){ return -1; } else{ if(this.getFirstName().compareTo(o.getFirstName())>0){ return 1; } else if(this.getFirstName().compareTo(o.getFirstName())<0){ return -1; } else{ return 0; } } return 0; }
-
Using comparable in a method in the main method
I am trying to check the values of a comparable method and assign the 1 and -1 value to true and false. I made a simple if else statement that does just that but I want to make it inside of a method so I can use it multiple times in my main method. When I try to do this I get an error that my compareTo method (in another class) is "undefined for the type Object".
Here is my code for both the compareTo method and my attempt of using this in my test class.
public int compareTo(FPNumber o) { if ((exp == o.exp) && (fraction - o.fraction < SMALL)) return 1; else if ((exp == o.exp) || (fraction - o.fraction > SMALL)) return -1; else return 0; }
public String compare(Object FP1, Object FP2) { if (FP1.compareTo(FP2) == 1) System.out.println("true"); else if (FP1.compareTo(FP2) == -1) System.out.println("false"); else System.out.println("error"); }
-
Functionality similar to Java TreeSet.floor() in Python 3
I am trying to solve a problem wherein I am given a bunch of days and some jobs to do within those days. Each job has a day deadline before which it has to be finished. As such, when I am assigning jobs to days I can assign the particular job to any day on or before its deadline. I can do this by maintaining an array of days and checking which day is available from deadline going back to day 1 (will have to do this for each job). Hence this method would take up
O(N^2)
time. However if I can use something like a TreeSet in Java which returns the floor value of a searched day (so if I search for day 5 but it already has a job assigned to it and the next free day is day 3,TreeSet.floor(5)
returns 3), that would take up onlylog N
time for the search part reducing it to anO(N log N)
operation.Is there any data structure available in Python3 wherein I can directly use this (without having to implement a TreeSet altogether)?
-
TreeSet Sorting Order Confusion
I know that TreeSet in Java sort its elements in ascending order. For integer it would be 1, 2, 3, 4, 5, for String it would be alphabetical. However, what if I want to input objects in that TreeSet, how it is going to be sorted by default?