Cursor to this method - android-room

error: Not sure how to convert a Cursor to this method's return type
(android.arch.lifecycle.LiveData>).
#Dao
public interface NoteDao {
#Insert
void insert(Note note);
#Update
void update(Note note);
#Delete
void delete(Note note);
#Query("DELETE FROM note_table")
void deleteAllNotes();
#Query("SELECT * FROM note_table ORDER BY priority DESC")
LiveData<List<Note>> getAllNotes();
}
How to fix it?

When using androidx.room.* please make sure to use androidx.lifecycle.LiveData instead of android.arch.lifecycle.LiveData or downgrade to pre-AndroidX versions of Room

Related

Can I have #Transactional multiple times in same method call

I'm new to Transactional Management, and I have a requirement that I might have to update the same column in DB with in the same call..
Here is what I have :
#Override
public void updateData(Keys keys) {
update1(keys);
update2(keys);
}
#Transactional
private void update1(Keys kesy) {
if(StringUtils.isNotBlank(keys.getValue1())) {
repo.updateKey1(keys.getValue1());
}
}
#Transactional
private void update2(Keys keys) {
if(StringUtils.isNotBlank(keys.getValue2())) {
repo.updateKey2(keys.getValue2());
}
}
I wrote it like this because I might get the same result for both methods, and I want to commit the data every time and get the lastest data
Any help is much appriciated.
I'm not sure if i understood your question right, but if you want to have both update calls in one transaction, it would be enough to annotate the updateData method with #Transactional:
#Override
#Transactional
public void updateData(Keys keys) {
update1(keys);
update2(keys);
}

I am getting internal server error dont konw reason for that

my code.....this was controller
controller
#Getmapping("/Transferabalance/{id}")
public List<Transaction> transfer(#PathVariable("Accbalance") long Accbalance) throws ResourceNotFoundException
{
List<Transaction> balance=Transservice.findByAccbalance(Accbalance);
if(balance==null)
throw new ResourceNotFoundException("NO BALANCE");
else
return balance;
}
This was service service
public List<Transaction> findByAccbalance(long Accbalance)
{
// TODO Auto-generated method stub
return transrepo.findByAccbalance(Accbalance);
}
transaction repository i used an query to retrive the elemnt from data base
public interface TransactionRepository extends CrudRepository<Transaction,Long>
{
#Query(value="select ACCBALANCE from TRANSACTION",nativeQuery = true)
List<Transaction> findByAccbalance(long Accbalance);
}
1st of all, CrudRepository itself provides you lots of methods to perform operation then why use JPQL though your query is simple.
you can simply use findByAccbalance(long Accbalance) that will return you expected result in your case.
List<Transaction> findByAccbalance(long Accbalance);
but if you wanna use Query then can you check with below Query:--
#Query(value="select c from TRANSACTION c")
List<Transaction> findByAccbalance(long Accbalance);

Transportation layer that support Polymorphism and Generics

I am looking for transportation layer for gwt. I would like to create ajax request using generic method, f.e this is my DAO/service:
public class GenericDao<T extends GenericModel<T>> {
private Logger logger = LoggerFactory.getLogger(this.getClass().getCanonicalName());
#Transient protected Class<T> entityClass;
public GenericDao() {
super();
}
public GenericDao(Class<? extends GenericModel<T>> clazz) {
this.entityClass = (Class<T>) clazz;
}
public T getBy(Long id) {
return JPA.em().find(entityClass, id);
}
public List<GenericModel<T>> get() {
logger.error("trying to get data from db");
return getList();
}
public List<GenericModel<T>> getList() {
return JPA.em().createQuery("FROM " + entityClass.getSimpleName()).getResultList();
}
public void save(GenericModel<T> entityClass) {
JPA.em().getTransaction().begin();
JPA.em().persist(entityClass);
JPA.em().getTransaction().commit();
}
public void update(T entityClass) {
JPA.em().getTransaction().begin();
JPA.em().merge(entityClass);
JPA.em().getTransaction().commit();
}
public void delete(T entityClass) {
JPA.em().getTransaction().begin();
JPA.em().remove(entityClass);
JPA.em().getTransaction().commit();
}
}
GenericModel/Entity:
#MappedSuperclass
public class GenericModel<T extends GenericModel<T>> implements Identifiable, Versionable {
#Transient
protected Class<T> entityClass;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Version
private Integer version;
// setter & getter
#Override
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
#Override
public Integer getVersion() {return version;}
public void setVersion(Integer version) {this.version = version;}
// constructor
public GenericModel() {
Class<?> obtainedClass = getClass();
Type genericSuperclass = null;
for (;;) {
genericSuperclass = obtainedClass.getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
break;
}
obtainedClass = obtainedClass.getSuperclass();
}
ParameterizedType genericSuperclass_ = (ParameterizedType) genericSuperclass;
try {
entityClass = ((Class) ((Class) genericSuperclass_
.getActualTypeArguments()[0]));
} catch (ClassCastException e) {
entityClass = guessEntityClassFromTypeParametersClassTypedArgument();
}
}
public GenericModel(Long id) {
this();
this.id = id;
}
}
I am looking for mechanism that will allow me to use this generic service for all models on client side (each db entity have id- so I would like to downloads using ajax all my Entities this way, so I should have only one generic method for that on client side).
I've already checked:
GWT-RPC
RequestFactory
RestyGWT
But none of them support this feature.
I've found here:
https://www.mail-archive.com/google-web-toolkit#googlegroups.com/msg100095.html
information that: gwt-jackson supports generics and polymorphism. Unfortunately I didn't found any working example that. Can someone help, give an example, approved that information?
All entities have id and version parameter. So I would like to have one metod on client side RF that will allow me to get from server(service/dao/whatever) that entity by id- like this: Request getBy(Long id); But unfortunatelly I can't make it work. I like the RF way, so I've tried it first. Generally I don't wonna repeat code for downloading entity/proxy by id.
For better understanding, please look also on:
RequestFactory client-side inheritance of typed class with generics
I'm confused as to why you think RPC can't handle generics - according to your link, it can, but RestyGWT cannot. Granted, none of your JPA references make any sense in GWT, but those would live in a DAO on the server, not in the entity/model class themselves, or at least not in the client version. If you had a RPC method that returned T where <T extends GenericModel<T>>, then you would have serializers for every possible GenericModel<?> subtype, and any/all that are gwt-compatible could be sent over the wire.
Edit from update to question:
Your GenericModel class uses features of Java that cannot work in GWT, such as reflection. This cannot be compiled to GWT, since the compiler relies on removing reflection information to minimize your compiled size - leaving in general reflection information means leaving in details about all classes and members, even ones that it can't statically prove are in use, since some reflection might make use of them.
If there is a way to phrase your model object in a way that just deals with the data at hand, focus on that. Otherwise consider a DTO which is just the data to send over the wire - I'm not sure how you would plan to use the entityClass field on the client, or why that would be important to read from the superclass's generics instead of just using getClass().
RequestFactory will have a hard time dealing with generics - unlike RPC (and possibly RestyGWT) it cannot handle polymorphism the way you want, but will instead only send the fields for the declared type, not any arbitrary subtype. RPC will actually send the instance if it is something that the client can handle.

DbUnit check autogenerating id

I need to execute integration tests using DbUnit. I have created to datasets (before and after test) and compare them using #DatabaseSetup and #ExpectedDatabase annotations. During test one new database row was created (it presents in after test dataset, which I specify using #ExpectedDatabase annotation). The problem is that row id is generating automatically (I am using Hibernate), so row id is changing permanently. Therefore my test pass only once and after that I need to change id in after test dataset, but this is not that I need. Can you suggest me please any solutions for this issue, if this issue can be resolved with DbUnit.
Solution A:
Use assigned id strategy and use a seperate query to retrieve next value in business logic. So you can always assign a known id in your persistence tests with some appropriate database cleanup. Note that this only works if you're using Oracle Sequence.
Solution B:
If I'm not mistaken, there are some methods similar to assertEqualsIngoreColumns() in org.dbunit.Assertion. So you can ignore the id assertion if you don't mind. Usually I'll compensate that with a not null check on id. Maybe there some options in #ExpectedDatabase but I'm not sure.
Solution C:
I'd like to know if there is a better solution because that solution A introduces some performance overhead while solution B sacrifices a little test coverage.
What version of dbunit you're using by the way. I have never seen these annotations in 2.4.9 and below, they looks easier to use.
This workaround is saving my skin till now:
I implemented a AbstractDataSetLoader with replacement feature:
public class ReplacerDataSetLoader extends AbstractDataSetLoader {
private Map<String, Object> replacements = new ConcurrentHashMap<>();
#Override
protected IDataSet createDataSet(Resource resource) throws Exception {
FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
builder.setColumnSensing(true);
try (InputStream inputStream = resource.getInputStream()) {
return createReplacementDataSet(builder.build(inputStream));
}
}
/**
* prepare some replacements
* #param dataSet
* #return
*/
private ReplacementDataSet createReplacementDataSet(FlatXmlDataSet dataSet) {
ReplacementDataSet replacementDataSet = new ReplacementDataSet(dataSet);
//Configure the replacement dataset to replace '[null]' strings with null.
replacementDataSet.addReplacementObject("[null]", null);
replacementDataSet.addReplacementObject("[NULL]", null);
replacementDataSet.addReplacementObject("[TODAY]", new Date());
replacementDataSet.addReplacementObject("[NOW]", new Timestamp(System.currentTimeMillis()));
for (java.util.Map.Entry<String, Object> entry : replacements.entrySet()) {
replacementDataSet.addReplacementObject("["+entry.getKey()+"]", entry.getValue());
}
replacements.clear();
return replacementDataSet;
}
public void replace(String replacement, Object value){
replacements.put(replacement, value);
}
}
With this you could somehow track the ids you need and replace in your testes
#DatabaseSetup(value="/test_data_user.xml")
#DbUnitConfiguration(dataSetLoaderBean = "replacerDataSetLoader")
public class ControllerITest extends WebAppConfigurationAware {
//reference my test dbconnection so I can get last Id using regular query
#Autowired
DatabaseDataSourceConnection dbUnitDatabaseConnection;
//reference my datasetloader so i can iteract with it
#Autowired
ColumnSensingFlatXMLDataSetLoader datasetLoader;
private static Number lastid = Integer.valueOf(15156);
#Before
public void setup(){
System.out.println("setting "+lastid);
datasetLoader.replace("emp1", lastid.intValue()+1);
datasetLoader.replace("emp2", lastid.intValue()+2);
}
#After
public void tearDown() throws SQLException, DataSetException{
ITable table = dbUnitDatabaseConnection.createQueryTable("ids", "select max(id) as id from company.entity_group");
lastid = (Number)table.getValue(0, "id");
}
#Test
#ExpectedDatabase(value="/expected_data.xml", assertionMode=DatabaseAssertionMode.NON_STRICT)
public void test1() throws Exception{
//run your test logic
}
#Test
#ExpectedDatabase(value="/expected_data.xml", assertionMode=DatabaseAssertionMode.NON_STRICT)
public void test2() throws Exception{
//run your test logic
}
}
And my expected dataset need some replacement emp1 and emp2
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
<company.entity_group ID="15155" corporate_name="comp1"/>
<company.entity_group ID="15156" corporate_name="comp2"/>
<company.entity_group ID="[emp1]" corporate_name="comp3"/>
<company.entity_group ID="[emp2]" corporate_name="comp3"/>
<company.ref_entity ID="1" entity_group_id="[emp1]"/>
<company.ref_entity ID="2" entity_group_id="[emp2]"/>
</dataset>
Use DatabaseAssertionMode.NO_STRICT, and delete the 'id' column from your 'expect.xml'.
DBUnit will ignore this column.

How automatically update fields like created/modified Date when using MyBatis?

I am using MyBatis and want to implement 2 fields on every table 'created', 'modified'. Both off them are date fields. Is there a way of automatically update these fields on an insert or update? Of course, I can adjust the mappings, but I was wondering if there is a more generic and DRY way of doing this?
No, mybatis has no mechanism to do this automatically without you coding your sql maps to update the columns.
One alternative would be database triggers. I'm not certain I would recommend that though, we just code it in the sql maps.
You could code it in the SQL maps like this,
<insert id="someInsert">
insert into dummy_table
(
SOME_COLUMN,
CREATED_DT
)
values
(
#{someValue},
sysdate
)
</insert>
or,
<update id="someUpdate">
update some_table
set some_column = #{someValue}, modified=sysdate
where some_id = #{someId}
</update>
you can use mybatis Interceptor
here is my example (using springboot):
in mycase, BaseEntity is the super class of all entity,i need do some thing before update or insert to database by mybatis.
step 1: create init method in BaseEntity for update or insert
public class BaseEntity{
private Date created;
private Date updated;
//getter,setter
public void initCreateEntity() {
this.created = new Date()
this.updated = new Date()
}
public void initUpdateEntity() {
this.created = new Date()
this.updated = new Date()
}
}
step 2: add a mybatis interceptor
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
/**
* add time interceptor for update
*/
#Intercepts(#Signature(type = Executor.class, method = "update", args={MappedStatement.class, Object.class}))
public class BaseEntityInterceptor implements Interceptor {
#Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
// get sql
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
// get parameter , this is the target object that you want to handle
Object parameter = invocation.getArgs()[1];
// make sure super class is BaseEntity
if (parameter instanceof BaseEntity) {
//init
BaseEntity baseEntity = (BaseEntity) parameter;
if (SqlCommandType.INSERT.equals(sqlCommandType)) {
baseEntity.initCreateEntity();
} else if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
baseEntity.initUpdateEntity();
}
}
return invocation.proceed();
}
#Override
public Object plugin(Object o) {
return Plugin.wrap(o, this);
}
#Override
public void setProperties(Properties properties) {
}
}
step 3: add to bean Context in springboot config
#Configuration
public class MyBatisConfig {
#Bean
public BaseEntityInterceptor baseEntityInterceptor() {
return new BaseEntityInterceptor();
}
}
step 4: Dao and Mapper.xml
//base update or insert sql incloude column created and updated
eg:Dao
#Mapper
public interface BaseDao {
int update(BaseEntity baseEntity);
}
Mapper.xml
<update id="update" parameterType="com.package.to.BaseEntity">
update baseentity_table set created = #{createTime, jdbcType=TIMESTAMP}
updated = #{createTime, jdbcType=TIMESTAMP}
</update>
step 5: test
baseDao.update(new BaseEntity);
More information here: https://mybatis.org/mybatis-3/configuration.html#plugins

Resources