how to save data in data base table has two primary key using jpa spring boot angular js - angularjs

THIS IS MY ENTITY
my probelem is i don't knwo why my http requtte dosn't work
i'm using ARC application to test the requette this is the error
"status": 500,
"error": "Internal Server Error",
"exception":"org.springframework.beans.ConversionNotSupportedException",
"message": "Failed to convert property value of type 'java.lang.Long' to required type 'com.projet.pfe.entities.AF' for property 'fa'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.Long' to required type 'com.projet.pfe.entities.AF' for property 'fa': no matching editors or conversion strategy found",
"path": "/saveactaf/2/2/333"
package com.projet.pfe.entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#IdClass(ActiviteAF.class)
#Entity
public class ActiviteAF implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#ManyToOne
#JoinColumn(name="idact")
private Activite activite;
#Id
#ManyToOne
#JoinColumn(name="idaf")
private AF fa;
private double montant;
public Activite getActivite() {
return activite;
}
public void setActivite(Activite activite) {
this.activite = activite;
}
public AF getFa() {
return fa;
}
public void setFa(AF fa) {
this.fa = fa;
}
public double getMontant() {
return montant;
}
public void setMontant(double montant) {
this.montant = montant;
}
public ActiviteAF(Activite activite, AF fa, double montant) {
super();
this.activite = activite;
this.fa = fa;
this.montant = montant;
}
public ActiviteAF() {
super();
}
}
this is my Repository
package com.projet.pfe.DAO;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.projet.pfe.entities.ActiviteAF;
public interface ActiviteAFRepository extends JpaRepository<ActiviteAF,Long> {
#Query("select af from ActiviteAF af where af.activite.idActivite like :x")
public Collection<ActiviteAF> activitebyid(#Param("x") Long id);
}
this is the Rest Controller
package com.projet.pfe.service;
import com.projet.pfe.DAO.AFRepository;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.projet.pfe.DAO.ActiviteAFRepository;
import com.projet.pfe.DAO.ActiviteRepository;
import com.projet.pfe.entities.AF;
import com.projet.pfe.entities.Activite;
import com.projet.pfe.entities.ActiviteAF;
import org.springframework.web.bind.annotation.PathVariable;
#RestController
public class ActAFRestService {
#Autowired
private ActiviteAFRepository actafmet;
#Autowired
private ActiviteRepository actr;
#Autowired
private AFRepository afr;
#RequestMapping(value="/saveactaf/{idact}/{idaf}/{montant}",method=RequestMethod.POST)
public ActiviteAF save(#PathVariable(name="idact")long idact,#PathVariable(name="idaf")long idaf,#PathVariable(name="montant")double montant){
Activite a = new Activite();
AF af = new AF();
a = actr.findOne(idact);
af = afr.findOne(idaf);
ActiviteAF aaf = new ActiviteAF(a,af,montant);
return actafmet.save(aaf);
}
}

I find a solution , juste make a singel. Id and change the others to a simple annotation(forign keys) , this solution work but need a test( activite,af ) in the case of adding new object .

Related

Remove item from a RecyclerView list based on status of a checkbox

I have a list application what is uses RecyclerView.
Each line has got a button, a checkbox and 2 textview.
All object is defined the RecyclerView clas, but I would like to check the checkbox status in the Main class and evaluate the status and remove the item from the list and from the SharedPreferences where the checkbox is checked
Main class is here:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ToDoList extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener, View.OnClickListener {
public MyRecyclerViewAdapter adapter;
public Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
public LinkedList<String> items, remain_days, prio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist);
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = findViewById(R.id.button);
items = new LinkedList<>();
remain_days = new LinkedList<>();
prio = new LinkedList<>();
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this,items,remain_days,prio);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
btn.setOnClickListener(this);
StartDisplay();
}
#Override
public void onItemClick(View view, int position) {
}
#Override
public void onClick(View v) {
Intent NewTLItem = new Intent(ToDoList.this, NewTLItem.class);
startActivity(NewTLItem);
}
#Override
public void onResume() {
super.onResume();
StartDisplay();
}
public void StartDisplay()
{
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
Map<String, ?> allEntries = sharedPreferences.getAll();
items.clear();
prio.clear();
remain_days.clear();
for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
String key_word = entry.getKey();
String [] item_total = entry.getValue().toString().split(";");
if(key_word.contains("_")) key_word = key_word.replace("_"," ");
items.add(key_word);
remain_days.add(Long.toString(DateCalc(item_total[0])));
prio.add(item_total[1]);
}
adapter.notifyDataSetChanged();
}
public long DateCalc(String startdate)
{
Date system_date, due_date;
long diff_date = 0;
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
try {
system_date = dates.parse(currentDate);
due_date = dates.parse(startdate);
diff_date = (due_date.getTime()-system_date.getTime())/86400000;
} catch (ParseException e) {
e.printStackTrace();
}
return diff_date;
}
}
At now the item is removed when the whole line is touched. I would like to exchange to if only the Checkbox is "true".
At now the remove method is in the public void onItemClick(View view, int position) function.
I would like to put the content of the OnItemClick method to "if" part of CheckBox status.
Here is the RecyclerView class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>
{
public List<String> mData, subdata, subdata2;
public LayoutInflater mInflater;
public ItemClickListener mClickListener;
public Context context;
public CheckBox done;
MyRecyclerViewAdapter(Context context, List<String> data, List<String> subdata, List<String> subdata2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.subdata = subdata;
this.subdata2 = subdata2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String meta_data = mData.get(position);
String meta_subdata = subdata.get(position);
String meta_subdata2 = subdata2.get(position);
holder.myTextView.setText(meta_data);
holder.subtext.setText(meta_subdata +" "+ meta_subdata2);
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] item_param = holder.myTextView.getText().toString().split(" ");
final Intent intent;
intent = new Intent(context, NewSLItem.class);
intent.putExtra("param",item_param[0]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public TextView myTextView, subtext;
public Button add;
public ViewHolder(View itemView)
{
super(itemView);
context = itemView.getContext();
myTextView = itemView.findViewById(R.id.tvAnimalName);
subtext = itemView.findViewById(R.id.subtext);
add = itemView.findViewById(R.id.add);
done = itemView.findViewById(R.id.done);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener
{
void onItemClick(View view, int position);
}
}
if(adapter.done.isChecked())should work I think, but I got null opbject reference exception.
Maybe the problem is that the checkbox is in the RecyclerView layout and not in Main class layout, but I am not sure.
Is it possible to handle the Checkbox methods from other class, and if yes, then where should I improve the code?

how to Initialization sequence generator _id in spring data mongo

i'm using spring boot + spring data mongodb and set Auto Generator Service ...
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Getter
#Setter
#Document(collection = "auto_sequence")
public class AutoIncrementSequence {
#Id
private String id;
private Long seq;
}
and
package com.juhyun.shorturl.entity.sequence;
import lombok.RequiredArgsConstructor;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import java.util.Objects;
import static org.springframework.data.mongodb.core.FindAndModifyOptions.options;
import static org.springframework.data.mongodb.core.query.Criteria.where;
#RequiredArgsConstructor
#Service
public class SequenceGeneratorService {
private final MongoOperations mongoOperations;
public Long generateSequence(String key) {
AutoIncrementSequence counter = mongoOperations.findAndModify(Query.query(where("_id").is(key)),
new Update().inc("seq", 1), options().returnNew(true).upsert(true), AutoIncrementSequence.class);
//return BigInteger.valueOf(!Objects.isNull(counter) ? counter.getSeq() : 1);
return !Objects.isNull(counter) ? counter.getSeq() : 1;
}
}
Entity
public class ShortUrl {
#Transient
public static final String SEQUENCE_NAME = "shorturl_sequence";
#Id
private Long _id;
If the return value of the generateSequence method of class SequenceGeneratorService is changed to 1L, it will be solved, but I wonder if there is any other way.
Thank you :)
Change return value only 1L in SequenceGeneratorService generateSequence method
Change sequence number in collection (I was using mongodb compass)

Room can't build database in Android Studio I can't figure out what's wrong?

I use a Room database class on Android Studio.
I have the following entities:
User, Address, Geo, Company, Album, Photo, AlbumPhotoCrossRef (there's many-to-many relationship between Album and Photo). And I added Word too just to test.
The code for these entities are added below.
When I use only Word (comment out other classes in the entities = part, it works, I can see the table via DatabaseInspector.
But when include all entities, the database don't even open, I can't even see name of the database on DatabaseInspector.
And I get the following error:
E/AndroidRuntime: FATAL EXCEPTION: pool-2-thread-1
Process: com.example.lab8_2_room_albums, PID: 8775
java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
at androidx.room.RoomOpenHelper.checkIdentity(RoomOpenHelper.java:154)
at androidx.room.RoomOpenHelper.onOpen(RoomOpenHelper.java:135)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.onOpen(FrameworkSQLiteOpenHelper.java:142)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:427)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:316)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:92)
at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:53)
at androidx.room.RoomDatabase.inTransaction(RoomDatabase.java:476)
at androidx.room.RoomDatabase.assertNotSuspendingTransaction(RoomDatabase.java:281)
at com.example.lab8_2_room_albums.dao.WordDao_Impl.insert(WordDao_Impl.java:57)
at com.example.lab8_2_room_albums.MainActivity.lambda$onCreate$0(MainActivity.java:59)
at com.example.lab8_2_room_albums.-$$Lambda$MainActivity$h9d6n2GFmqhE1uxj4ezb0-bRXOU.run(Unknown Source:2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
I/Process: Sending signal. PID: 8775 SIG: 9
It refers to the line in the MainActivity where I run dao.insert(word) also where I insert a word. into database.
I did clean the project, rebuld the project too, but I still get the same error. Why? How to figure out what's wrong? And how can I fix this?
The database class is like below:
package com.example.lab8_2_room_albums.db;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.example.lab8_2_room_albums.dao.PhotoDAO;
import com.example.lab8_2_room_albums.dao.UserDAO;
import com.example.lab8_2_room_albums.dao.WordDao;
import com.example.lab8_2_room_albums.entities.Address;
import com.example.lab8_2_room_albums.entities.Album;
import com.example.lab8_2_room_albums.entities.AlbumPhotoCrossRef;
import com.example.lab8_2_room_albums.entities.Company;
import com.example.lab8_2_room_albums.entities.Geo;
import com.example.lab8_2_room_albums.entities.Photo;
import com.example.lab8_2_room_albums.entities.User;
import com.example.lab8_2_room_albums.entities.Word;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
#Database(entities = {Word.class, User.class, Address.class, Geo.class, Company.class, Album.class, Photo.class, AlbumPhotoCrossRef.class}, version = 1, exportSchema = true)
public abstract class UserRoomDatabase extends RoomDatabase {
//public abstract UserDAO userDAO();
// public abstract PhotoDAO photoDAO();
public abstract WordDao wordDao();
// volatile: har sammenheng med multithreading. Sikrer at alle trĂ¥der ser samme kopi av INSTANCE.
private static volatile UserRoomDatabase INSTANCE;
private static final int NUMBER_OF_THREADS = 4;
public static final ExecutorService databaseWriteExecutor =
Executors.newFixedThreadPool(NUMBER_OF_THREADS);
public static UserRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (UserRoomDatabase.class) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
UserRoomDatabase.class, "mydaaatabase")
.addCallback(sRoomDatabaseCallback)
.build();
}
}
return INSTANCE;
}
private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {
/**
* Called when the database is created for the first time.
* This is called after all the tables are created.
* #param db
*/
#Override
public void onCreate(#NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
// If you want to keep data through app restarts,
// comment out the following block
databaseWriteExecutor.execute(() -> {
// Populate the database in the background.
WordDao wordDao = INSTANCE.wordDao();
//wordDao.deleteAll();
wordDao.insert(new Word("asd"));
wordDao.insert(new Word("adsds"));
wordDao.getAlphabetizedWords();
});
}
#Override
public void onOpen(#NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
}
};
/*
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
#Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE user "
+ " ADD COLUMN birth_year INTEGER");
}
};*/
}
And here's the Main Activity:
package com.example.lab8_2_room_albums;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.room.Room;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import com.example.lab8_2_room_albums.dao.PhotoDAO;
import com.example.lab8_2_room_albums.dao.UserDAO;
import com.example.lab8_2_room_albums.dao.WordDao;
import com.example.lab8_2_room_albums.databinding.ActivityMainBinding;
import com.example.lab8_2_room_albums.db.UserRoomDatabase;
import com.example.lab8_2_room_albums.entities.Address;
import com.example.lab8_2_room_albums.entities.Album;
import com.example.lab8_2_room_albums.entities.AlbumWithPhotos;
import com.example.lab8_2_room_albums.entities.Company;
import com.example.lab8_2_room_albums.entities.Geo;
import com.example.lab8_2_room_albums.entities.Photo;
import com.example.lab8_2_room_albums.entities.User;
import com.example.lab8_2_room_albums.entities.UserWithAlbums;
import com.example.lab8_2_room_albums.entities.UserWithCompanyWithAddressWithGeo;
import com.example.lab8_2_room_albums.entities.Word;
import com.example.lab8_2_room_albums.viewmodel.UserAlbumsViewModel;
public class MainActivity extends AppCompatActivity {
private UserAlbumsViewModel userAlbumsViewModel;
private ActivityMainBinding activityMainBinding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ViewBinding:
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
activityMainBinding = ActivityMainBinding.inflate(layoutInflater);
setContentView(activityMainBinding.getRoot());
// userAlbumsViewModel = new ViewModelProvider(this).get(UserAlbumsViewModel.class);
UserRoomDatabase db = UserRoomDatabase.getDatabase(this);
WordDao dao = db.wordDao();
UserRoomDatabase.databaseWriteExecutor.execute(() -> {
// Populate the database in the background.
// If you want to start with more words, just add them.
Word word = new Word("Helloooo");
dao.insert(word);
word = new Word("Woooorld");
dao.insert(word);
dao.getAlphabetizedWords();
});
}
}
I add some words into the words table in database. It works without any problem.
Word class:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity(tableName = "word_table")
public class Word {
#PrimaryKey
#NonNull
#ColumnInfo(name = "word")
private String mWord;
public Word(#NonNull String word) {this.mWord = word;}
public String getWord(){return this.mWord;}
}
WordDAO:
package com.example.lab8_2_room_albums.dao;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import com.example.lab8_2_room_albums.entities.Word;
import java.util.List;
#Dao
public interface WordDao {
// allowing the insert of the same word multiple times by passing a
// conflict resolution strategy
#Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(Word word);
#Query("DELETE FROM word_table")
void deleteAll();
#Query("SELECT * FROM word_table ORDER BY word ASC")
LiveData<List<Word>> getAlphabetizedWords();
}
User class:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
#Entity(foreignKeys = {
#ForeignKey(entity = Address.class, parentColumns = "addressId", childColumns = "fk_addressId", onDelete = ForeignKey.CASCADE),
#ForeignKey(entity = Company.class, parentColumns = "companyId", childColumns = "fk_companyId", onDelete = ForeignKey.CASCADE)
})
public class User {
#PrimaryKey(autoGenerate = true)
public long userId;
public String name;
public String username;
public String email;
public long fk_addressId;
public String phone;
public String website;
public long fk_companyId;
public User(#NonNull String name, #NonNull String username, #NonNull String email, long fk_addressId,
#NonNull String phone, #NonNull String website, long fk_companyId) {
this.name = name;
this.username = username;
this.email = email;
this.fk_addressId = fk_addressId;
this.phone = phone;
this.website = website;
this.fk_companyId = fk_companyId;
}
}
Address:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
#Entity(foreignKeys = {
#ForeignKey(entity = Geo.class, parentColumns = "geoId", childColumns = "fk_geoId", onDelete = ForeignKey.CASCADE)
})
public class Address {
#PrimaryKey(autoGenerate = true)
public long addressId;
public String street;
public String suite;
public String city;
public String zipCode;
public long fk_geoId;
public Address(#NonNull String street, #NonNull String suite, #NonNull String city,
#NonNull String zipCode, long fk_geoId) {
this.street = street;
this.suite = suite;
this.city = city;
this.zipCode = zipCode;
this.fk_geoId = fk_geoId;
}
}
Geo:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity
public class Geo {
#PrimaryKey(autoGenerate = true)
public long geoId;
public double lat;
public double lng;
public Geo(#NonNull double lat, #NonNull double lng) {
this.lat = lat;
this.lng = lng;
}
}
Company:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity
public class Company {
#PrimaryKey(autoGenerate = true)
public long companyId;
public String name;
public String catchPhrase;
public String bs;
public Company(#NonNull String name, #NonNull String catchPhrase, #NonNull String bs) {
this.name = name;
this.catchPhrase = catchPhrase;
this.bs = bs;
}
}
Album:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;
#Entity(foreignKeys = {
#ForeignKey(entity = User.class, parentColumns="userId", childColumns = "fk_userId", onDelete = ForeignKey.CASCADE)
})
public class Album {
#PrimaryKey(autoGenerate = true)
public long albumId;
public long fk_userId;
public String title;
public Album(#NonNull String title, long fk_userId) {
this.title = title;
this.fk_userId = fk_userId;
}
}
Photo:
package com.example.lab8_2_room_albums.entities;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
#Entity
public class Photo {
#PrimaryKey(autoGenerate = true)
public long photoId;
public String title;
public String url;
public String thumbnailUrl;
public Photo(#NonNull String title, #NonNull String url, #NonNull String thumbnailUrl) {
this.title = title;
this.url = url;
this.thumbnailUrl = thumbnailUrl;
}
}
AlbumPhotoCrossRef:
package com.example.lab8_2_room_albums.entities;
import androidx.room.Entity;
import androidx.room.ForeignKey;
#Entity(primaryKeys = {"albumId", "photoId"},
foreignKeys = {
#ForeignKey(entity = Album.class, parentColumns="albumId", childColumns = "albumId", onDelete = ForeignKey.CASCADE),
#ForeignKey(entity = Photo.class, parentColumns="photoId", childColumns = "photoId", onDelete = ForeignKey.CASCADE)
}
)
public class AlbumPhotoCrossRef {
public long albumId;
public long photoId;
}
You've changed the schema (structure) without changing the version number. Room's integrity checking has detected the change and hence the exception.
As you have MIGRATION_1_2 you probably just need to change the version number from 1 to 2 as per :-
#Database(entities = {Word.class, User.class, Address.class, Geo.class, Company.class, Album.class, Photo.class, AlbumPhotoCrossRef.class}, version = 2, exportSchema = true
The message in the log basically says the above bar about having a migration available as per :-
java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number.
However, looking at the migration it's altering the user table by adding a column. This doesn't appear to cover the changes you say you have made (added Word entity/table). You may wish to consider the alternative.
The alternative is to uninstall the App and rerun and the new schema will be applied (not any good if the App has been published as any data will be lost).
Room undertakes this checking by the use of a table called room_master_table this table stores an identity hash which is generated according to the schema that room builds/maintains from the code. Change the schema (code) and the hash changes. If the hash mismatches and the version number is not changed then the exception (or similar in the case of down grade)

Cannot Unit Test Using Fongo fails in 4.1.4 - worked in 3.1.4

https://github.com/sanjuthomas/spring-data-mongodb
I have try several examples such as the one above to understand how to unit test mongo applications using fongo. All the examples examples worked - including the one above but when I upgrade the pom to the latest releases supported in spring boot all the examples fail. It seems the application context is no longer getting loaded for the test. Is this unit test functionality broken or do I need to change the code?
Below is the code that fails and used to work in Spring 3 - now the rule fails stating that a mongo instance does not exist in the context:
package com.ourownjava.spring.data.mongo.repository;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.foursquare.fongo.Fongo;
import com.lordofthejars.nosqlunit.annotation.ShouldMatchDataSet;
import com.lordofthejars.nosqlunit.annotation.UsingDataSet;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import com.mongodb.Mongo;
import com.ourownjava.spring.data.mongo.model.Trade;
/**
* Spring Data MongoDB Repository Unit testcase.
*
* #author ourownjava.com
*
*/
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
public class TestTradeRepository {
#Autowired
private ApplicationContext applicationContext;
#Rule
public MongoDbRule mongoDbRule = newMongoDbRule().defaultSpringMongoDb(
"trade-db");
#Autowired
private TradeRepository tradeRepository;
#Test
#ShouldMatchDataSet(location = "/testData/trade-t1.json")
public void shouldSaveTrade(){
tradeRepository.save(createTrade());
}
#Test
#UsingDataSet(locations = {"/testData/trade-t1.json"})
public void shouldFindByTraderId(){
final List<Trade> trades = tradeRepository.findByTraderId("papjac");
assertNotNull(trades);
assertTrue(trades.size() > 0);
assertEquals("papjac", trades.get(0).getTraderId());
}
#Test
#UsingDataSet(locations = {"/testData/trade-t1.json"})
public void shouldFindByExchangeCode(){
final List<Trade> trades = tradeRepository.findByExchangeCode("NYSE");
assertNotNull(trades);
assertTrue(trades.size() > 0);
assertEquals("NYSE", trades.get(0).getExchangeCode());
}
private Trade createTrade(){
final Trade trade = new Trade();
trade.setId("t1");
trade.setTraderId("papjac");
trade.setExchangeCode("NYSE");
trade.setValue(90.3);
return trade;
}
#Configuration
#EnableMongoRepositories
#ComponentScan(basePackageClasses = { TradeRepository.class })
static class MongoConfiguration extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "trade-db";
}
#Override
public Mongo mongo() {
return new Fongo("trade-test").getMongo();
}
#Override
protected String getMappingBasePackage() {
return "com.ourownjava.spring.data.mongo";
}
}
}
You have to use Annotation #Bean for mongo()
#Bean
#Override
public Mongo mongo() {
return new Fongo("trade-test").getMongo();
}

I want to convert csv file to xml

I want to convert csv file to xml and i want to send the converted xml file to a queue in activemq..Is there any sample code or any reference websites or blogs please help to find sample code for this program..
Use the Bindy and Xstream components. From http://workingwithqueues.blogspot.ch/2012/07/converting-csv-to-xml-with-camel-bindy.html (with a JMS endpoint instead of a file endpoint):
DataFormat bindy = new BindyCsvDataFormat("com.package.dto");
from("file://TEST?fileName=Employee.csv")
.unmarshal(bindy)
.marshal()
.xstream()
.to("jms:queue:FOO.BAR");
For connecting to JMS have a look at the JMS and ActiveMQ components.
package org.mycompany.conversion;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Greeting {
#XmlElementWrapper(name = "Person")
#XmlElement(name = "persons")
private List<Person> persons;
public List<Person> getPerson() {
return persons;
}
public void setPerson(List<Person> persons) {
this.persons = persons;
}
}
========================================================================================
package org.mycompany.conversion;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#CsvRecord(separator = ",")
public class Person {
#DataField(pos = 1)
#XmlElement
private int id;
#DataField(pos = 2)
#XmlElement
private String name;
#DataField(pos = 3)
#XmlElement
private int age;
#Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
======================================================================================
package org.mycompany.conversion;
import javax.xml.bind.JAXBContext;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.converter.jaxb.JaxbDataFormat;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spi.DataFormat;
public class CsvConversion {
public static void main(String[] args) throws Exception {
JaxbDataFormat xmlDataFormat = new JaxbDataFormat();
JAXBContext con = JAXBContext.newInstance(Greeting.class);
xmlDataFormat.setContext(con);
DataFormat bindy = new BindyCsvDataFormat(Person.class);
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
#Override
public void configure() throws Exception {
from("file:src/main/data/in/csv?noop=true").split().tokenize("\n").unmarshal(bindy)
// constanr(true):-aggregate all using same expression
.aggregate(constant(true), new AttachAggregation())
//mandatory after aggregate
.completionTimeout(100)//end after this gives problem
.marshal(xmlDataFormat).log("xml body is ${body}")
.to("file:src/main/data/in/xml?fileName=convertedXml.xml");// .aggregate(new
// AttachAggreagation());
}
});
context.start();
Thread.sleep(5000);
}
}
=========================================================================================
package org.mycompany.conversion;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.Exchange;
import org.apache.camel.processor.aggregate.AggregationStrategy;
public class AttachAggregation implements AggregationStrategy {
List<Person> list = new ArrayList();
Greeting gre = new Greeting();
#Override
//person-address
// greeting-user
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
Person newBody1 = newExchange.getIn().getBody(Person.class);
list.add(newBody1);
return newExchange;
} else {
Person newBody2 = newExchange.getIn().getBody(Person.class);
list.add(newBody2);
gre.setPerson(list);
oldExchange.getIn().setBody(gre);
return oldExchange;
}
}
}

Resources