E/SQLiteLog: (1) duplicate column name: Temperatur - duplicates

I just started to work with android studio. i am also new in the programming of apps or anything else. Now i try to build my first app. i get the failure massage: "E/SQLiteLog: (1) duplicate column name: Temperatur"
In the other Threads i don´t find the right solution.
My Code:
public class FangbuchDbHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "fangbuch.db";
public static final int DB_Version = 1;
public static final String TABLE_KARPFEN = "Karpfen";
public static final String COLUMN_ID = "id";
public static final String COLUMN_DATUM = "Datum";
public static final String COLUMN_ZEIT = "Uhrzeit";
public static final String COLUMN_WINDRICHTUNG = "Windrichtung";
public static final String COLUMN_WINDSTAERKE = "Windstärke bft";
public static final String COLUMN_TEMPERATURA = "Temperatur außen";
public static final String COLUMN_TEMPERATURW = "Temperatur Wasser";
public static final String COLUMN_HPAGESTERN = "hPa gestern";
public static final String COLUMN_HPAHEUTE = "hPa heute";
public static final String COLUMN_HPAMORGEN = "hPa morgen";
public static final String COLUMN_MOND = "Mond";
public static final String COLUMN_GEWICHT = "Gewicht";
public static final String COLUMN_FOTO = "Foto";
public static final String TABLE_MEERFORELLE = "Meerforelle";
public static final String COLUMN_ID2 = "id2";
public static final String COLUMN_DATUM2 = "Datum2";
public static final String COLUMN_ZEIT2 = "Zeit2";
public static final String COLUMN_WASSERSTAND = "Wasserstand";
public static final String COLUMN_WINDSTAERKE2 = "Windstärke2 bft";
public static final String COLUMN_WINDRICHTUNG2 = "Windrichtung2";
public static final String COLUMN_TEMPERATURW2 = "Wassertemperatur";
public static final String COLUMN_STROEMUNG = "Strömung";
public static final String COLUMN_FOTO2 = "Foto2";
public static final String SQL_CREATE =
"create table " + TABLE_KARPFEN + "(" +
COLUMN_ID + " integer primary key , " +
COLUMN_DATUM + " text not null, " +
COLUMN_ZEIT + " text, " +
COLUMN_WINDRICHTUNG + " text, " +
COLUMN_WINDSTAERKE + " integer, " +
COLUMN_TEMPERATURA + " integer, " +
COLUMN_TEMPERATURW + " integer not null, " +
COLUMN_HPAGESTERN + " integer, " +
COLUMN_HPAHEUTE + " integer, " +
COLUMN_HPAMORGEN + " integer, " +
COLUMN_MOND + " text, " +
COLUMN_GEWICHT + " REAL, " +
COLUMN_FOTO + " text); ";
public static final String SQL_CREATE2 =
"create table " + TABLE_MEERFORELLE + "(" +
COLUMN_ID2 + " integer, " +
COLUMN_DATUM2 + " text not null, " +
COLUMN_ZEIT2 + " text, " +
COLUMN_WASSERSTAND + " text, " +
COLUMN_WINDSTAERKE2 + "integer, " +
COLUMN_WINDRICHTUNG2 + " text, " +
COLUMN_TEMPERATURW2 + " integer, " +
COLUMN_STROEMUNG + " text, " +
COLUMN_FOTO2 + " text); ";
public FangbuchDbHelper(#Nullable Context context) {
super(context, DB_NAME, null, DB_Version);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE);
sqLiteDatabase.execSQL(SQL_CREATE2);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(FangbuchDbHelper.class.getName(), "Upgrading database from version " + oldVersion + "to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + DB_NAME);
onCreate(db);
}
}
At the beginning i had duplicate column names. But now i have changed this.
But i still get this message.
Whats my mistake? Can someone help me? Thanks
Regards Ulf

I'm not a SQL(ite) expert, but it's noticeable that your column names Temperatur außen and Temperatur Wasser contain a space and are inserted unquoted in the create table statement, which presumably causes the error. According to SQLite Keywords, there are three or four ways of quoting an identifier in SQLite - you may want to choose one for the definitions of COLUMN_TEMPERATURA and COLUMN_TEMPERATURW.

perhaps this activities can help:
public class DbEntry {
//Karpfen Spalten Variablen
private long id;
private String Datum;
private String Zeit;
private String Windrichtung;
private int Windstaerke;
private int TemperaturA;
private int TemperaturW;
private int hPaGestern;
private int hPaHeute;
private int hPaMorgen;
private String Mond;
private float Gewicht;
//Meerforellen Spalten Variablen
private long id2;
private String Datum2;
private String Zeit2;
private String Wasserstand;
private int Windstaerke2;
private String Windrichtung2;
private int TemperaturW2;
private String Stroemung;
//get und set für Karpfentabelle
public long getId() {
return id;
}
public void setId (long id){
this.id = id;
}
public String getDatum() {
return Datum;
}
public void setDatum(String string) {
this.Datum = Datum;
}
public String getZeit() {
return Zeit;
}
public void setZeit(String string) {
this.Zeit = Zeit;
}
public String getWindrichtung() {
return Windrichtung;
}
public void setWindrichtung(String string) {
this.Windrichtung = Windrichtung;
}
public int getWindstaerke() {
return Windstaerke;
}
public void setWindstaerke(int anInt) {
this.Windstaerke = Windstaerke;
}
public int getTemperaturA() {
return TemperaturA;
}
public void setTemperaturA(int anInt) {
this.TemperaturA = TemperaturA;
}
public int getTemperaturW() {
return TemperaturW;
}
public void setTemperaturW(int anInt) {
this.TemperaturW = TemperaturW;
}
public int gethPaGestern() {
return hPaGestern;
}
public void sethPaGestern(int anInt) {
this.hPaGestern = hPaGestern;
}
public int gethPaHeute() {
return hPaHeute;
}
public void sethPaHeute(int anInt) {
this.hPaHeute = hPaHeute;
}
public int gethPaMorgen() {
return hPaMorgen;
}
public void sethPaMorgen(int anInt) {
this.hPaMorgen = hPaMorgen;
}
public String getMond() {
return Mond;
}
public void setMond(String string) {
this.Mond = Mond;
}
public float getGewicht() {
return Gewicht;
}
public void setGewicht(float aFloat) {
this.Gewicht = Gewicht;
}
//get und set für Meerforellen Tabelle
public long getId2() {
return id2;
}
public void setId2(long aLong) {
this.id2 = id2;
}
public String getDatum2() {
return Datum2;
}
public void setDatum2(String string) {
this.Datum2 = Datum2;
}
public String getZeit2() {
return Zeit2;
}
public void setZeit2(String string) {
this.Zeit2 = Zeit2;
}
public String getWasserstand() {
return Wasserstand;
}
public void setWasserstand(String string) {
this.Wasserstand = Wasserstand;
}
public int getWindstaerke2() {
return Windstaerke2;
}
public void setWindstaerke2(int anInt) {
this.Windstaerke2 = Windstaerke2;
}
public String getWindrichtung2() {
return Windrichtung2;
}
public void setWindrichtung2(String string) {
this.Windrichtung2 = Windrichtung2;
}
public int getTemperaturW2() {
return TemperaturW2;
}
public void setTemperaturW2(int anInt) {
this.TemperaturW2 = TemperaturW2;
}
public String getStroemung() {
return Stroemung;
}
public void setStroemung(String string) {
this.Stroemung = Stroemung;
}
}
or this activity:
public class DbDataSource {
private SQLiteDatabase fbDatabase;
private FangbuchDbHelper dbHelper;
private String[] allColumnsKarpfen = {"COLUMN_ID", "COLUMN_DATUM", "COLUMN_ZEIT", "COLUMN_WINDRICHTUNG", "COLUMN_WINDSTAERKE",
"COLUMN_TEMPERATURA", "COLUMN_TEMPERATURW", "COLUMN_HPAGESTERN", "COLUMN_HPAHEUTE", "COLUMN_HPAMORGEN", "COLUMN_MOND",
"COLUMN_GEWICHT"};
private String[] allColumnsMeerforelle = {"COLUMN_ID2", "COLUMN_DATUM2", "COLUMN_ZEIT2", "COLUMN_WASSERSTAND", "COLUMN_WINDSTAERKE2",
"COLUMN_WINDRICHTUNG2", "COLUMN_TEMPERATURW2", "COLUMN_STROEMUNG"};
public DbDataSource(Context context) {
dbHelper = new FangbuchDbHelper(context);
}
public void open() throws SQLException {
fbDatabase = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public DbEntry createEntryKarpfen(String Datum, String Zeit, String Windrichtung, int Windstaerke, int TemperaturA, int TemperaturW,
int hPaGestern, int hPaHeute, int hPaMorgen, String Mond, float Gewicht) {
ContentValues values = new ContentValues();
values.put("COLUMN_DATUM", Datum);
values.put("COLUMN_ZEIT", Zeit);
values.put("COLUMN_WINDRICHTUNG", Windrichtung);
values.put("COLUMN_WINDSTAERKE", Windstaerke);
values.put("COLUMN_TEMPERATURA", TemperaturA);
values.put("COLUMN_TEMPERATURW", TemperaturW);
values.put("COLUMN_HPAGESTERN", hPaGestern);
values.put("COLUMN_HPAHEUTE", hPaHeute);
values.put("COLUMN_HPAMORGEN", hPaMorgen);
values.put("COLUMN_MOND", Mond);
values.put("COLUMN_GEWICHT", Gewicht);
long insertId = fbDatabase.insert("TABLE_KARPFEN", null, values);
Cursor cursor = fbDatabase.query("TABLE_KARPFEN", allColumnsKarpfen, "COLUMN_ID = " + insertId, null, null, null, null);
cursor.moveToFirst();
return cursorToDbEntryKarpfen(cursor);
}
public DbEntry createEntryMeerforelle(String Datum2, String Zeit2, String Wasserstand, int Windstaerke2, String Windrichtung2, int TemperaturW2,
String Stroemung) {
ContentValues values2 = new ContentValues();
values2.put("COLUMN_DATUM2", Datum2);
values2.put("COLUMN_ZEIT2", Zeit2);
values2.put("COLUMN_WASSERSTAND", Wasserstand);
values2.put("COLUMN_WINDSTAERKE2", Windstaerke2);
values2.put("COLUMN_WINDRICHTUNG2", Windrichtung2);
values2.put("COLUMN_TEMPERATURW2", TemperaturW2);
values2.put("COLUMN_STROEMUNG", Stroemung);
long insertId2 = fbDatabase.insert("TABLE_MEERFORELLE", null, values2);
Cursor cursorMeerforelle = fbDatabase.query("TABLE_MEERFORELLE", allColumnsMeerforelle, "COLUMN_ID2 = " + insertId2, null, null, null, null);
cursorMeerforelle.moveToFirst();
return cursorToDbEntryMeerforelle(cursorMeerforelle);
}
protected List<DbEntry> getKarpfenEntries() {
List<DbEntry> EntryKarpfenList = new ArrayList<DbEntry>();
EntryKarpfenList = new ArrayList<DbEntry>();
Cursor cursor = fbDatabase.query("TABLE_KARPFEN", allColumnsKarpfen, null,null, null, null, null);
cursor.moveToFirst();
if(cursor.getCount() == 0) return EntryKarpfenList;
while (cursor.isAfterLast() == false) {
DbEntry entry = cursorToDbEntryKarpfen(cursor);
EntryKarpfenList.add(entry);
cursor.moveToNext();
}
cursor.close();
return EntryKarpfenList;
}
protected List<DbEntry> getMeerforelleEntries() {
List<DbEntry> EntryMeerforelleList = new ArrayList<DbEntry>();
EntryMeerforelleList = new ArrayList<DbEntry>();
Cursor cursor = fbDatabase.query("TABLE_MEERFORELLE", allColumnsMeerforelle, null,null, null, null, null);
cursor.moveToFirst();
if(cursor.getCount() == 0) return EntryMeerforelleList;
while (cursor.isAfterLast() == false) {
DbEntry entry = cursorToDbEntryKarpfen(cursor);
EntryMeerforelleList.add(entry);
cursor.moveToNext();
}
cursor.close();
return EntryMeerforelleList;
}
private DbEntry cursorToDbEntryKarpfen(Cursor cursor) {
DbEntry entry = new DbEntry();
entry.setId(cursor.getLong(0));
entry.setDatum(cursor.getString(1));
entry.setZeit(cursor.getString(2));
entry.setWindrichtung(cursor.getString(3));
entry.setWindstaerke(cursor.getInt(4));
entry.setTemperaturA(cursor.getInt(5));
entry.setTemperaturW(cursor.getInt(6));
entry.sethPaGestern(cursor.getInt(7));
entry.sethPaHeute(cursor.getInt(8));
entry.sethPaMorgen(cursor.getInt(9));
entry.setMond(cursor.getString(10));
entry.setGewicht(cursor.getFloat(11));
return entry;
}
private DbEntry cursorToDbEntryMeerforelle(Cursor cursor) {
DbEntry entry2 = new DbEntry();
entry2.setId2(cursor.getLong(0));
entry2.setDatum2(cursor.getString(1));
entry2.setZeit2(cursor.getString(2));
entry2.setWasserstand(cursor.getString(3));
entry2.setWindstaerke2(cursor.getInt(4));
entry2.setWindrichtung2(cursor.getString(5));
entry2.setTemperaturW2(cursor.getInt(6));
entry2.setStroemung(cursor.getString(7));
return entry2;
}
}

Related

convert MultipartFile to required type byte[] thymeleaf error

im getting this error idk why
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='client'. Error count: 1
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'client' on field 'image': rejected value [org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile#42df4d2d]; codes [typeMismatch.client.image,typeMismatch.image,typeMismatch.[B,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [client.image,image]; arguments []; default message [image]]; default message [Failed to convert property value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'byte[]' for property 'image'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile' to required type 'byte' for property 'image[0]': PropertyEditor [org.springframework.beans.propertyeditors.CustomNumberEditor] returned inappropriate value of type 'org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile']
Entity :
#Entity
#Table(name = "Client")
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="idClient")
private Long idClient;
#Column(name="nom")
private String nomClient;
#Column(name="prenom")
private String prenomClient;
#Column(name="datedenaissance")
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Temporal(TemporalType.DATE)
private Date datedenaissanceClient;
#Column(name="typepiece")
private String typepieceClient;
#Column(name="numeropiece")
private int numeropieceClient;
#Column(name="numerotel")
private Long numerotelClient;
#Column(name="email")
private String emailClient;
#Column(name="adresse")
private String adresseClient;
#Column(name="rendezvous")
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Temporal(TemporalType.DATE)
private Date rendezvous;
#Column(name="temps")
#DateTimeFormat(pattern = "hh:mm")
#Temporal(TemporalType.TIME)
private Date temps;
#Column(name="tempsfin")
#DateTimeFormat(pattern = "hh:mm")
#Temporal(TemporalType.TIME)
private Date tempsfin;
#OneToMany(cascade = CascadeType.ALL, mappedBy="clients")
private List<Compte> comptes;
#Lob
#Column(name="image")
private byte[] image;
public static long getSerialversionuid() {
return serialVersionUID;
}
public Long getIdClient() {
return idClient;
}
public void setIdClient(Long idClient) {
this.idClient = idClient;
}
public String getNomClient() {
return nomClient;
}
public void setNomClient(String nomClient) {
this.nomClient = nomClient;
}
public String getPrenomClient() {
return prenomClient;
}
public void setPrenomClient(String prenomClient) {
this.prenomClient = prenomClient;
}
public Date getDatedenaissanceClient() {
return datedenaissanceClient;
}
public void setDatedenaissanceClient(Date datedenaissanceClient) {
this.datedenaissanceClient = datedenaissanceClient;
}
public String getTypepieceClient() {
return typepieceClient;
}
public void setTypepieceClient(String typepieceClient) {
this.typepieceClient = typepieceClient;
}
public Date getTempsfin() {
return tempsfin;
}
public void setTempsfin(Date tempsfin) {
this.tempsfin = tempsfin;
}
public int getNumeropieceClient() {
return numeropieceClient;
}
public void setNumeropieceClient(int numeropieceClient) {
this.numeropieceClient = numeropieceClient;
}
public Long getNumerotelClient() {
return numerotelClient;
}
public void setNumerotelClient(Long numerotelClient) {
this.numerotelClient = numerotelClient;
}
public String getEmailClient() {
return emailClient;
}
public void setEmailClient(String emailClient) {
this.emailClient = emailClient;
}
public String getAdresseClient() {
return adresseClient;
}
public void setAdresseClient(String adresseClient) {
this.adresseClient = adresseClient;
}
public Date getRendezvous() {
return rendezvous;
}
public void setRendezvous(Date rendezvous) {
this.rendezvous = rendezvous;
}
public Date getTemps() {
return temps;
}
public void setTemps(Date temps) {
this.temps = temps;
}
public List<Compte> getComptes() {
return comptes;
}
public void setComptes(List<Compte> comptes) {
this.comptes = comptes;
}
public Client(Long idClient, String nomClient, String prenomClient, Date datedenaissanceClient,
String typepieceClient, int numeropieceClient, Long numerotelClient, String emailClient,
String adresseClient, Date rendezvous, Date temps, Date tempsfin, List<Compte> comptes, byte[] image) {
super();
this.idClient = idClient;
this.nomClient = nomClient;
this.prenomClient = prenomClient;
this.datedenaissanceClient = datedenaissanceClient;
this.typepieceClient = typepieceClient;
this.numeropieceClient = numeropieceClient;
this.numerotelClient = numerotelClient;
this.emailClient = emailClient;
this.adresseClient = adresseClient;
this.rendezvous = rendezvous;
this.temps = temps;
this.tempsfin = tempsfin;
this.comptes = comptes;
this.image = image;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
#Override
public String toString() {
return "Client [idClient=" + idClient + ", nomClient=" + nomClient + ", prenomClient=" +
prenomClient
+ ", datedenaissanceClient=" + datedenaissanceClient + ", typepieceClient=" +
typepieceClient
+ ", numeropieceClient=" + numeropieceClient + ", numerotelClient=" + numerotelClient +
", emailClient="
+ emailClient + ", adresseClient=" + adresseClient + ", rendezvous=" + rendezvous + ",
temps=" + temps
+ ", tempsfin=" + tempsfin + ", comptes=" + comptes + ", image=" + Arrays.toString(image)
+ "]";
}
public Client() {
super();
// TODO Auto-generated constructor stub
}
public Client(Long idClient, String nomClient, String prenomClient, Date datedenaissanceClient,
String typepieceClient, int numeropieceClient, Long numerotelClient, String emailClient,
String adresseClient, Date rendezvous, Date temps, List<Compte> comptes) {
super();
this.idClient = idClient;
this.nomClient = nomClient;
this.prenomClient = prenomClient;
this.datedenaissanceClient = datedenaissanceClient;
this.typepieceClient = typepieceClient;
this.numeropieceClient = numeropieceClient;
this.numerotelClient = numerotelClient;
this.emailClient = emailClient;
this.adresseClient = adresseClient;
this.rendezvous = rendezvous;
this.temps = temps;
this.comptes = comptes;
}
}
Service :
#Override
public void addClient(Client client){
// TODO Auto-generated method stub
this.clientRepository.save(client);
}
Controller :
#RequestMapping(value = { "/saveClient" }, method = RequestMethod.POST, consumes = {"multipart/form-data"})
public String saveClient(#ModelAttribute("client") Client client,Model model,#ModelAttribute("compte") Compte compte,#ModelAttribute("carte") Carte carte,
#ModelAttribute("agence") Agence agence,MultipartHttpServletRequest request,final #RequestParam("image") MultipartFile file) throws IOException {
compte.setClients(client);
String uploadDirectory = request.getServletContext().getRealPath(uploadFolder);
log.info("uploadDirectory:: " + uploadDirectory);
String fileName = file.getOriginalFilename();
String filePath = Paths.get(uploadDirectory, fileName).toString();
log.info("FileName: " + file.getOriginalFilename());
if (fileName == null || fileName.contains("..")) {
model.addAttribute("invalid", "Sorry! Filename contains invalid path sequence \" + fileName");
}
try {
File dir = new File(uploadDirectory);
if (!dir.exists()) {
log.info("Folder Created");
dir.mkdirs();
}
// Save the file locally
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
stream.write(file.getBytes());
stream.close();
} catch (Exception e) {
log.info("in catch");
e.printStackTrace();
}
byte[] imageData = file.getBytes();
client.setImage(imageData);
Date v = client.getTemps();
//Date dNow = new Date( ); // Instantiate a Date object
Calendar cal = Calendar.getInstance();
cal.setTime(v);
cal.add(Calendar.AM_PM, 0);
cal.add(Calendar.MINUTE, 30);
v = cal.getTime();
client.setTempsfin(v);
clientMetier.addClient(client);
compteMetier.addCompte(compte);
agence.setCompteagence(compte);
compte.setAgencecompte(agence);
agenceMetier.addAgence(agence);
model.addAttribute("compte",compte);
model.addAttribute("agence",agence);
return "compte";
}
HTML:
<form th:action="#{/saveClient}" method="POST"
th:object="${client}" enctype="multipart/form-data">
<div class="p-col-12">
<label class="p1">Image</label>
<input type="file" class="form-control" placeholder="" name="image" id="image" th:field="*{image}">
You should not directly use your entity as the form object as you need to use different types for the image.
Create a separate ClientFormData object to use in the controller that has all the fields of Client, but for image uses MultipartFile:
public class ClientFormData {
// other fields here
private MultipartFile image;
public static ClientFormData fromClient(Client client) {
// copy over fields
}
}
In the controller, get the bytes from the MultipartFile and copy those into your Client entity.

#Query keep pulling null from database

I am currently having what I'd like to call as Code Block (Writer block but with coding). I have tried to check many times and make sure that everything is in the proper place but it keeps getting me a null despite the data that I ask in the #Query is exist.
This is the #Query that I currently have,
#Query(value = "select d.denda from data_transaksi_model d WHERE d.tanggal=:x AND d.nama_wp = :y AND d.masa_pajak=:z", nativeQuery = true)
String findAllDenda(String x,String y,String z);
My expected output from there is a collection of "denda" from the table of "data_transaksi_model" which has the specific "tanggal", "name", and "masa_pajak" from that table. I have double checked the table that is created within the database and it has the same name as to what I inquire there,
As you can see, the table name is matchup and the name of the column name that has the name of what I want in my query is also match up. Just to make sure, I also check the structure of the database and it is indeed a string, also the same with others.
The table is the byproduct of the model from my Spring Boot's project that I have made.
#Entity
public class DataTransaksiModel {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#NotNull
#Column(name = "tanggal")
private String tanggal;
#NotNull
#Column(name = "no_kohir")
private String noKohir;
#NotNull
#Column(name = "no_urut")
private String noUrut;
#NotNull
#Column(name = "nama_wp")
private String namaWP;
#NotNull
#Column(name = "jam")
private String jam;
#NotNull
#Column(name = "nop")
private String nop;
#NotNull
#Column(name = "denda")
private String denda;
#NotNull
#Column(name = "jumlah_setoran")
private String jumlahSetoran;
#NotNull
#Column(name = "luas_tanah")
private String luasTanah;
#NotNull
#Column(name = "luas_bangunan")
private String luasBangunan;
#NotNull
#Column(name = "kecamatan")
private String kecamatan;
#NotNull
#Column(name = "kelurahan")
private String kelurahan;
#NotNull
#Column(name = "masa_pajak")
private String masaPajak;
#NotNull
#Column(name = "lokasi")
private String lokasi;
#NotNull
#Column(name = "pokok")
private String pokok;
#NotNull
#Column(name = "cabang")
private String cabang;
#NotNull
#Column(name = "User")
private String user;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTanggal() {
return tanggal;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public String getNoKohir() {
return noKohir;
}
public void setNoKohir(String noKohir) {
this.noKohir = noKohir;
}
public String getNoUrut() {
return noUrut;
}
public void setNoUrut(String noUrut) {
this.noUrut = noUrut;
}
public String getNamaWP() {
return namaWP;
}
public void setNamaWP(String namaWP) {
this.namaWP = namaWP;
}
public String getJam() {
return jam;
}
public void setJam(String jam) {
this.jam = jam;
}
public String getNop() {
return nop;
}
public void setNop(String nop) {
this.nop = nop;
}
public String getDenda() {
return denda;
}
public void setDenda(String denda) {
this.denda = denda;
}
public String getJumlahSetoran() {
return jumlahSetoran;
}
public void setJumlahSetoran(String jumlahSetoran) {
this.jumlahSetoran = jumlahSetoran;
}
public String getLuasTanah() {
return luasTanah;
}
public void setLuasTanah(String luasTanah) {
this.luasTanah = luasTanah;
}
public String getLuasBangunan() {
return luasBangunan;
}
public void setLuasBangunan(String luasBangunan) {
this.luasBangunan = luasBangunan;
}
public String getKecamatan() {
return kecamatan;
}
public void setKecamatan(String kecamatan) {
this.kecamatan = kecamatan;
}
public String getKelurahan() {
return kelurahan;
}
public void setKelurahan(String kelurahan) {
this.kelurahan = kelurahan;
}
public String getMasaPajak() {
return masaPajak;
}
public void setMasaPajak(String masaPajak) {
this.masaPajak = masaPajak;
}
public String getLokasi() {
return lokasi;
}
public void setLokasi(String lokasi) {
this.lokasi = lokasi;
}
public String getPokok() {
return pokok;
}
public void setPokok(String pokok) {
this.pokok = pokok;
}
public String getCabang() {
return cabang;
}
public void setCabang(String cabang) {
this.cabang = cabang;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
With that finished, I insert a data dummy into the database as the following.
Therefore, I tried to put the input of tanggal with "1170130", nama_wp with "SURATNO" and masa_pajak with "2016". However, I keep getting null instead of "9.166" in the collection. Where did I do wrong? I am using XAMPP, MySQL, and Spring Boot for this project.
/EDIT: I tried it manually in my XAMPP with SELECT denda FROM data_transaksi_modelWHERE nama_wp="SURATNO" AND masa_pajak="2014" AND tanggal="1170130" and it actually gives me a return
However, when I do it in my spring boot project it still return null.
//Edit2: I am using IntelliJ as my IDE and there is a warning (not an error) within the #Query annotation. It is said that "No data sources are configured to run this SQL and provide advanced code assistance. Disable this inspection via problem menu (alt+enter)" there is also a warning that said, "SQL dialect is not configured". If that is the source of the problem, how to fix it?
///edit3: I tried to fix around the query and it doesn't show the result that I wanted. This is the service that I am using for the repository
#Autowired
DataTransaksiDb dataTransaksiDb;
#Override
public List<String> getDenda(String tanggal, String nama, String masaPajak){
// TODO Auto-generated method stub
return dataTransaksiDb.findAllDenda(tanggal, nama, masaPajak);
}
and this is the controller where I am using the service. The controller is using a multipart file where the data is taken out from the CSV that is uploaded where within the CSV has the table that is the same as the database.
#PostMapping("/uploadFile")
public static void uploadFile(#RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
if (file.getContentType().equalsIgnoreCase("application/vnd.ms-excel")) {
InputStreamReader input = new InputStreamReader(file.getInputStream());
CSVParser csvParser = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(input);
for (CSVRecord record : csvParser) {
String nama = record.get("nama_wp");
String masa = record.get("masa_pajak");
String tanggal = record.get("tanggal");
String denda = record.get("denda");
String jumlahSetoran = record.get("jumlah_setoran");
String pokok = record.get("pokok");
String luasTanah = record.get("luas_tanah");
String luasBangunan = record.get("luas_bangunan");
try {
System.err.println(tanggal + "\n" + nama + "\n" + masa);
List<String> results = rekonsiliasiService.getDenda(tanggal, nama, masa);
System.err.println("results " + results);
} catch (NullPointerException e) {
System.err.println(e);
}
}
response.sendRedirect("/rekonsiliasi");
} else {
response.sendRedirect("/rekonsiliasi");
}
}
Whatever the result of the input that I get, it keep getting catches by the nullpointerexception
////EDIT4:
I tried debugging it and from my controller, I tried to do System.err.println(rekonsiliasiService.getDenda(tanggal,nama,masa)); and it keep me getting a NullPointerException. Then I tried to see if the problem is the input of the parameter itself within the service
#Override
public List<String> getDenda(String tanggal, String nama, String masaPajak){
// TODO Auto-generated method stub
System.err.println("tanggal " + tanggal + "\n" + "nama " + nama + "\n" + "masaPajak " + masaPajak);
return dataTransaksiDb.findAllDenda(tanggal, nama, masaPajak);
}
It never reached to the System.err.println("tanggal " + tanggal + "\n" + "nama " + nama + "\n" + "masaPajak " + masaPajak); within my Service layer.
try this :
#Query(value = "select d.denda from DataTransaksiModel d WHERE d.tanggal=:x AND d.namaWP = :y AND d.masaPajak=:z")
List<String> findAllDenda(#Param("x")String x, #Param("y")String y,#Param("z") String z);
if it didn't work try this :
#Query(value = "select d.denda from data_transaksi_model d WHERE d.tanggal=:x AND d.nama_wp = :y AND d.masa_pajak=:z", nativeQuery = true)
List<String> findAllDenda(#Param("x")String x, #Param("y")String y,#Param("z") String z);

One to many relation between two tables Spring boot JPA not working

I'm trying to create two tables Courses Table and Games Table. The course contains many games. The game is only assigned to one course.
I have defined the entities to do that on spring boot as follows:
Course Entity:
package play_and_learn.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
#Entity
#Table(name = "courses")
public class Course {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int courseId;
private String courseName;
private String courseDescription;
private String creatorTeacherUsername;
#OneToMany(mappedBy = "course", cascade = CascadeType.ALL)
private List<Game> courseGames;
public Course(String courseName, String courseDescription
, String creatorTeacherUsername, List<Game> courseGames) {
super();
this.courseName = courseName;
this.courseDescription = courseDescription;
this.creatorTeacherUsername = creatorTeacherUsername;
this.courseGames = courseGames;
}
public Course(String courseName, String courseDescription, String creatorTeacherUsername) {
super();
this.courseName = courseName;
this.courseDescription = courseDescription;
this.creatorTeacherUsername = creatorTeacherUsername;
this.courseGames = new ArrayList<Game>();
}
public Course(String courseName, String description) {
super();
this.courseName = courseName;
this.courseDescription = description;
this.creatorTeacherUsername = "";
this.courseGames = new ArrayList<Game>();
}
public Course () {
super();
this.courseName = "";
this.courseDescription = "";
this.courseGames = new ArrayList<>();
}
public void addGame(Game game) {
courseGames.add(game);
}
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
public void setCourseDescription(String courseDescription) {
this.courseDescription = courseDescription;
}
public String getCreatorTeacherUsername() {
return creatorTeacherUsername;
}
public void setCreatorTeacherUsername(String creatorTeacherUsername) {
this.creatorTeacherUsername = creatorTeacherUsername;
}
public List<Game> getCourseGames() {
return courseGames;
}
public void setCourseGames(List<Game> courseGames) {
this.courseGames = courseGames;
}
public Game getGameByID(int gameID) {
for (Game game : courseGames) {
if (game.getGameId() == gameID) {
return game;
}
}
return null;
}
// #Override
// public String toString() {
// return "Course [courseId=" + courseId + ", courseName=" + courseName
+ ", courseDescription="
// + courseDescription + ", courseGames=" + courseGames + "]";
// }
}
Game Entity
package play_and_learn.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
#Entity
#Table(name = "games")
public class Game {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int gameID;
private String name;
private String description;
private String creatorTeacherUsername;
private String gameType; // MCQ , True & False , etc.
protected int numOfQuestions = 0;
#ManyToOne
#JoinColumn(name = "courseId")
private Course course; // database related field
#OneToMany(mappedBy = "q_id", cascade = CascadeType.ALL)
protected List<Question> questions;
public Game() {
name="";
description="";
creatorTeacherUsername = "";
gameType = "";
numOfQuestions = 0;
questions = new ArrayList<>();
}
public Game(String name, String description, String creatorTeacherUsername
, String gameType, int numnumOfQuestions) {
this.name = name;
this.description = description;
this.creatorTeacherUsername = creatorTeacherUsername;
this.gameType = gameType;
this.numOfQuestions = numnumOfQuestions;
questions = new ArrayList<>();
}
public String getGameType() {
return gameType;
}
public void setGameType(String gameType) {
this.gameType = gameType;
}
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 int getGameId() {
return gameID;
}
public void setGameId(int id) {
this.gameID = id;
}
public String getCreatorTeacherUsername() {
return creatorTeacherUsername;
}
public void setCreatorTeacherUsername(String creatorTeacherUsername) {
this.creatorTeacherUsername = creatorTeacherUsername;
}
public int getNumOfQuestions() {
return numOfQuestions;
}
public void setNumOfQuestions(int numOfQuestions) {
this.numOfQuestions = numOfQuestions;
}
public List<Question> getQuestions() {
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
public void addQuestion(String qBody, String theRightAnswer, String ... answers) {
Question q = new Question();
q.setqBody(qBody);
q.setAnswer1(answers[0]);
q.setAnswer2(answers[1]);
q.setAnswer3(answers[2]);
q.setAnswer4(answers[3]);
q.setTheRighAnswer(theRightAnswer);
questions.add(q);
}
public void addQuestion(Question question) {
questions.add(question);
}
// #Override
// public String toString() {
// return "Game [gameID=" + gameID + ", name=" + name + ", description=" +
description
// + ", creatorTeacherUsername=" + creatorTeacherUsername + ",
gameType=" + gameType + ", numOfQuestions="
// + numOfQuestions + ", questions=" + questions + "]";
// }
}
However I always get no games inside my courses: (course_id is always null as in the picture)
MySql Query
What am I doing wrong in my entities?
Set also inverse relationship, i.e. set courseId for every game being added into relation.
public class Course{
...
public void addGame(Game game) {
courseGames.add(game);
game.setCourse(this);
}
Same way in constructor.

Am getting 'Field 'mui_profile_id' doesn't have a default value' while try to establish a OneToMany relationship in JPA

I am trying to establish a OneToMany relationship between User and UserIdentification where many identification records are to be saved against a user profile. am trying to save the mu_profile_id in the UserIdentification table as a foreign key named 'mui_profile_id'.
please find the below table structure.
List of User identification details are stored in user against a list UserIdentification entities.
CREATE TABLE a2b_mstr_user (
mu_id int(15) NOT NULL AUTO_INCREMENT,
mu_profile_id varchar(30) NOT NULL,
mu_user_id varchar(30) NOT NULL,
mu_password varchar(30) NOT NULL,
mu_first_name varchar(50) NOT NULL,
mu_last_name varchar(50) NOT NULL,
mu_gender varchar(1) NOT NULL,
mu_nationality varchar(30) NOT NULL,
mu_date_of_birth date NOT NULL,
mu_place_of_birth varchar(30) DEFAULT NULL,
mu_notes tinytext,
mu_status tinyint(4) DEFAULT NULL,
mu_locked tinyint(4) DEFAULT NULL,
mu_unsuc_log_attmpts int(1) DEFAULT NULL,
PRIMARY KEY (mu_id),
KEY last_name_ind (mu_last_name),
KEY profile_id_ind (mu_profile_id)
) ENGINE=InnoDB
User Identification Table
CREATE TABLE a2b_mstr_user_identification (
mui_identfcn_id int(15) NOT NULL AUTO_INCREMENT,
mui_profile_id varchar(30) NOT NULL,
mui_document_type varchar(30) NOT NULL,
mui_document_category varchar(30) DEFAULT NULL,
mui_document_no varchar(50) NOT NULL,
mui_country varchar(30) DEFAULT NULL,
mui_state varchar(30) DEFAULT NULL,
mui_valid_from date DEFAULT NULL,
mui_valid_to date DEFAULT NULL,
mui_status varchar(10) NOT NULL DEFAULT 'Y' COMMENT 'to determine the document is active or not. ''Y'' if ''Active'' and ''N'' if not active.',
PRIMARY KEY (mui_identfcn_id),
UNIQUE KEY DOCUMENT_NO_IND (mui_document_no),
KEY USER_IDENTIFICATION_FK (mui_profile_id),
CONSTRAINT USER_IDENTIFICATION_FK FOREIGN KEY (mui_profile_id) REFERENCES a2b_mstr_user (mu_profile_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB
and the entities for User.
#Entity
#Table(name="A2B_MSTR_USER")
public class User extends BaseEntity{
#Column(name="mu_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected String muId;
#Column(name="mu_profile_id")
protected String profileId;
#Column(name="mu_user_id")
#NotEmpty
protected String userId;
#Column(name="mu_password")
protected String password;
#Column(name="mu_first_name")
#NotEmpty
protected String firstName;
#Column(name="mu_last_name")
#NotEmpty
protected String lastName;
#Column(name="mu_gender")
#NotEmpty
protected String gender;
#Column(name="mu_nationality")
#NotEmpty
protected String nationality;
#Column(name="mu_date_of_birth")
protected Date dateOfBirth;
#Column(name="mu_place_of_birth")
protected String placeOfBirth;
#Column(name="mu_notes")
protected String notes;
#Column(name="mu_status")
protected Short status;
#Column(name="mu_locked")
protected boolean isLocked;
#Column(name="mu_unsuc_log_attmpts")
protected int unSucLogonAttmpts;
#OneToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL,mappedBy="user")
protected UserContact userContact;
#OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL,mappedBy="user")
protected List<UserAttachment> userAttachments;
#OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="mui_profile_id",insertable=true,updatable=true)
protected List<UserIdentification> userIdentificationDetails;
#PrePersist
protected void prePersist(){
if(getProfileId()==null){
setProfileId(new IdGenerator(10).nextString().toUpperCase());
}
}
public String getMuId() {
return muId;
}
public void setMuId(String muId) {
this.muId = muId;
}
public String getProfileId() {
return profileId;
}
public void setProfileId(String profileId) {
this.profileId = profileId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getPlaceOfBirth() {
return placeOfBirth;
}
public void setPlaceOfBirth(String placeOfBirth) {
this.placeOfBirth = placeOfBirth;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public UserContact getUserContact() {
return userContact;
}
public void setUserContact(UserContact userContact) {
this.userContact = userContact;
}
public Short getStatus() {
return status;
}
public void setStatus(Short status) {
this.status = status;
}
public boolean isLocked() {
return isLocked;
}
public void setLocked(boolean isLocked) {
this.isLocked = isLocked;
}
public int getUnSucLogonAttmpts() {
return unSucLogonAttmpts;
}
public void setUnSucLogonAttmpts(int unSucLogonAttmpts) {
this.unSucLogonAttmpts = unSucLogonAttmpts;
}
public List<UserAttachment> getUserAttachments() {
return userAttachments;
}
public void setUserAttachments(List<UserAttachment> userAttachments) {
this.userAttachments = userAttachments;
}
public List<UserIdentification> getUserIdentificationDetails() {
return userIdentificationDetails;
}
public void setUserIdentificationDetails(ArrayList<UserIdentification> userIdentificationDetails) {
this.userIdentificationDetails = userIdentificationDetails;
}
}
And the Entity for UserIdentification as follows.
#Entity
#Table(name="A2B_MSTR_USER_IDENTIFICATION")
public class UserIdentification extends BaseEntity {
#Column(name="mui_identfcn_id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer identificationId;
#Column(name="mui_document_type")
protected String documentType;
#Column(name="mui_document_category")
protected String documentCategory;
#Column(name="mui_document_no")
protected String documentNo;
#Column(name="mui_country")
protected String country;
#Column(name="mui_state")
protected String state;
#Column(name="mui_valid_from")
protected Date validFrom;
#Column(name="mui_valid_to")
protected Date validTo;
#Column(name="mui_status")
protected String status;
public Integer getIdentificationId() {
return identificationId;
}
public void setIdentificationId(Integer identificationId) {
this.identificationId = identificationId;
}
public String getDocumentType() {
return documentType;
}
public void setDocumentType(String documentType) {
this.documentType = documentType;
}
public String getDocumentCategory() {
return documentCategory;
}
public void setDocumentCategory(String documentCategory) {
this.documentCategory = documentCategory;
}
public String getDocumentNo() {
return documentNo;
}
public void setDocumentNo(String documentNo) {
this.documentNo = documentNo;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getValidFrom() {
return validFrom;
}
public void setValidFrom(Date validFrom) {
this.validFrom = validFrom;
}
public Date getValidTo() {
return validTo;
}
public void setValidTo(Date validTo) {
this.validTo = validTo;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "UserIdentification [identificationId=" + identificationId + ", documentType=" + documentType
+ ", documentCategory=" + documentCategory + ", documentNo=" + documentNo + ", country=" + country
+ ", state=" + state + ", validFrom=" + validFrom + ", validTo=" + validTo + ", status=" + status
+ ", user=" + "]";
}
}
When I am trying to save it using JPA, am getting the error Caused by: java.sql.SQLException: Field 'mui_profile_id' doesn't have a default value.

Expected BEGIN_OBJECT but was NUMBER

im receiving this json as response from an rest server:
{
"externalOrderId":"5cb9bc46-aaa3-43ff-bb1a-6b17443f63ea",
"shortId":null,
"createdAt":1442255497402,
"updatedAt":1442255497402,
"cart":{
"id":"gy4ectxb3db84epljzhisqrf"
}
}
Then, when i try to parse this json using gson.fromJson, i got the error:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was NUMBER at line 1 column 201 path $.createdAt
here is the how im doing it:
public Order getOrder(String externalOrderId) throws Exception {
HttpRequest request = new HttpRequestBuilder()
.setUrl(new URI(baseURL + "/order/" + externalOrderId))
.build();
return gson.fromJson(HttpResource.getInstance().get(request).getBody(), new TypeToken<Order>(){}.getType());
}
The Order object:
private String externalOrderId;
private Long shortId;
private Date createdAt;
private Date updatedAt;
Thanks in advance.
Your createdAt and updatedAt fields are Date objects, whereas the JSON data has numbers. To be able to match against the numbers, you'll need to have createdAt and updatedAt also be Longs and the convert them to Date objects later.
Try This (See toString and longToDate metods in Order.java) -
Cart.java
public class Cart {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public String toString() {
return "Cart [id=" + id + "]";
}
}
Order.java
import java.util.Date;
public class Order {
private String externalOrderId;
private Long shortId;
private Long createdAt;
private Long updatedAt;
private Cart cart;
public String getExternalOrderId() {
return externalOrderId;
}
public void setExternalOrderId(String externalOrderId) {
this.externalOrderId = externalOrderId;
}
public Long getShortId() {
return shortId;
}
public void setShortId(Long shortId) {
this.shortId = shortId;
}
public Long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Long createdAt) {
this.createdAt = createdAt;
}
public Long getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Long updatedAt) {
this.updatedAt = updatedAt;
}
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
private Date longToDate(Long dt) {
return new Date(dt);
}
#Override
public String toString() {
return "Order [externalOrderId=" + externalOrderId + ", shortId="
+ shortId + ", createdAt=" + longToDate(createdAt) + ", updatedAt="
+ longToDate(updatedAt) + ", cart=" + cart + "]";
}
}
Main.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Order;
public class Main {
private static Gson gson;
static {
gson = new GsonBuilder().create();
}
public static void main(String[] args) {
String j = "{\"externalOrderId\":\"5cb9bc46-aaa3-43ff-bb1a-6b17443f63ea\",\"shortId\":null,\"createdAt\":1442255497402,\"updatedAt\":1442255497402,\"cart\":{\"id\":\"gy4ectxb3db84epljzhisqrf\"}}";
Order r = gson.fromJson(j, Order.class);
System.out.println(r);
}
}
Result
Order [externalOrderId=5cb9bc46-aaa3-43ff-bb1a-6b17443f63ea, shortId=null, createdAt=Tue Sep 15 00:01:37 IST 2015, updatedAt=Tue Sep 15 00:01:37 IST 2015, cart=Cart [id=gy4ectxb3db84epljzhisqrf]]