I'm looking for a way to get all records where deleted is set to true on a particular table. How might I accomplish this?
Note: Using auto-generated class by SubSonic. Not T-SQL.
The auto-generated SubSonic classes don't support querying logical deletes. But you can do this (version 2.1/2.2 syntax):
public partial class TableClassCollection
{
public TableClassCollection LoadAll(bool suppressLogicalDeletes)
{
SubSonic.SqlQuery q = new SubSonic.Select(TableClass.Schema)
.From(TableClass.Schema);
if (suppressLogicalDeletes)
{
q.Where(TableClass.DeletedColumn).IsEqualTo(false);
}
return q.ExecuteAsCollection<TableClassCollection>();
}
}
More examples at subsonicproject.com
I've never heard of SubSonic before, but a quick Google search turned up: Select Queries in SubSonic.
So, using that page as a guide, it sounds like you'd be able to write your query as:
FooCollection deletedFoos = // use the generated collection class
DB.Select().From("FooTable") // table name goes here
.Where("deleted").IsEqualTo(true) // might need 1, depends on database?
.ExecuteAsCollection<FooCollection>(); // should match the type above
not a lot of detail in your question, but assuming there's a column named "deleted," it would look something like this:
select * from tableName where deleted = true
Related
I have a simple query as follows "select * from USERS". I also use Pageable to enable pagination.
This query may have optional predicates based on the given parameters being null or not.
For example if "code" parameter is given and not null, then the query becomes
"select * from USERS where code = :code";
As far as I know I cannot implement this using #Query annotation. I can implement a custom repository and use EntityManager to create a dynamic query.
However, I am not sure how I can integrate "Pageable" with that to get back paginated results.
How can I achieve this?
This is very easy to do in Spring Data using QueryDSL (as alternative to the criteria API). It is supported out of the box with the following method of QueryDSLPredicateExecutor where you can just pass null as the Predicate if no restrictions are to be applied:
Page<T> findAll(com.mysema.query.types.Predicate predicate,
Pageable pageable)
Using QueryDSL may not be an option for you however if you look at the following series of tutorials you might get some ideas.
http://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-nine-conclusions/
The scenario you have is actually discussed by the author in the comments to part 9 of his guide.
Getting page results for querydsl queries is somehow complicated since you need two queries: one for the total number of entries, and one for the list of entries you need in the page.
You could use the following superclass:
public class QueryDslSupport<E, Q extends EntityPathBase<E>> extends QueryDslRepositorySupport {
public QueryDslSupport(Class<E> clazz) {
super(clazz);
}
protected Page<E> readPage(JPAQuery query, Q qEntity, Pageable pageable) {
if (pageable == null) {
return readPage(query, qEntity, new QPageRequest(0, Integer.MAX_VALUE));
}
long total = query.clone(super.getEntityManager()).count(); // need to clone to have a second query, otherwise all items would be in the list
JPQLQuery pagedQuery = getQuerydsl().applyPagination(pageable, query);
List<E> content = total > pageable.getOffset() ? pagedQuery.list(qEntity) : Collections.<E> emptyList();
return new PageImpl<>(content, pageable, total);
}
}
You have to use querydsl and build your where depending on not null parameter for example
BooleanBuilder where = new BooleanBuilder();
...
if(code != null){
where.and(YOURENTITY.code.eq(code));
}
and after execute the query
JPAQuery query = new JPAQuery(entityManager).from(..)
.leftJoin( .. )
...
.where(where)
and use your own page
MaPage<YOURENTITY> page = new MaPage<YOURENTITY>();
page.number = pageNumber+1;
page.content = query.offset(pageNumber*pageSize).limit(pageSize).list(...);
page.totalResult = query.count();
I create MyPage like that
public class MaPage<T> {
public List<T> content;
public int number;
public Long totalResult;
public Long totalPages;
...
}
it works but if in your query you got a fetch then you gonna have this warning
nov. 21, 2014 6:48:54 AM org.hibernate.hql.internal.ast.QueryTranslatorImpl list
WARN: HHH000104: firstResult/maxResults specified with collection fetch; applying in memory!
and it will slow down your request So the solution is to get ride of the fetch and define a #BatchSize(size=10) and use Hibernate.initialize(....) to fetch data in collections and other object type.
Display data from related entities to avoid the lazy initialization exception with setting up #BatchSize
How to execute a JPAQuery with pagination using Spring Data and QueryDSL
The information here is obsolete. Have your Repository implement the QueryDslPredicateExecutor and paging comes for free.
I have a product entity and it has an images field that store the images names from the product but the images names depends of a part_number field that is unique, so if the user make a mistake in the part number and he wants to edit it then I also have to change the images names
I tried this but it does not works:
// class ProductsAdmin extends Admin
public function preUpdate($product) {
$old_product = $this->getSubject();
if ($old_product->getPartNumber() != $product->getPartNumber)
{
// change file names
}
$this->saveFile($product);
}
How I get the original row in preUpdate() function?
According to the topic taken from the official SonataAdmin google forum:
https://groups.google.com/forum/#!topic/sonata-devs/0zML6N13i3U
you need to make use of the class UnitOfWork:
http://www.doctrine-project.org/api/orm/2.3/class-Doctrine.ORM.UnitOfWork.html
Do this way:
public function preUpdate($object)
{
$em = $this->getModelManager()->getEntityManager($this->getClass());
$original = $em->getUnitOfWork()->getOriginalDocumentData($object);
}
Thus you get an array of values of your database entity.
E.g: to get access to the value password of your entity do:
$password = $original['password'];
That's all.
Enjoy :)
If you just do a doctrine query in the preUpdate function to get the product from the database you'll have the old object. Then do the comparison and you're good to go.
I've been checking ServiceStack's documentation, but I haven't found a way to do many to many relationships with ServiceStack.OrmLite, is it supported? Is there a workaround (without writing raw sql)?
I'd like to have something like this:
Article <- ArticleToTag -> Tag
Thanks!!
It's not implicitly handled automatically for you behind the scenes if that's what you mean? But as OrmLite is just a thin wrapper around ADO.NET interfaces anything is possible.
In OrmLite, by default every POCO maps 1:1 with a table. So if you wanted the table layout you would create it just as it looks in your database, e.g.
var article = new Article { ... };
var tag = new Tag { ... };
var articleTag = new ArticleTag { ArticleId = article.Id, TagId = tag.Id };
db.Insert(article, tag, articleTag);
Although you might want to take advantage of the built-in blobbing in OrmLite where any complex type just gets serialized and stored in a single text field. So you could do something like:
var article = { new Article { Tags = { "A","B","C" } };
Where Tags is just a List<string> and OrmLite will take care of transparently serializing it in the database field for you.
I want to get all conflict documents from a Notes database. So far, i've got this:
Domino.NotesSession notesSession;
Domino.NotesDatabase notesDatabase = this.OpenDatabase(out notesSession);
Domino.NotesDateTime dateTime = notesSession.CreateDateTime(String.Empty);
Domino.NotesDocumentCollection results =
notesDatabase.Search(this.SearchString, dateTime, 0);
It works with, for example:
searchString = "#Contains(ShortName;\"Bob\")";
How can I do the equivalent for conflict documents?
Try this:
searchString = "#IsAvailable($Conflict)";
There is a field on a document that flags any Notes document as a conflict called "$Conflict". If it's present on the document, then you know it's a conflict, (like Carlos is eluding to).
You can create a view in the database that has the formula.
Select #isAvailable("$Conflict")
and then loop through all documents in the view. It looks like you're doing it in Java so I think it would look like this
import lotus.domino.*;
import java.util.*;
//.....
//.....
Session s = NotesFactory.createSession();
Database db = s.getDatabase("server", "filename");
View vw = db.getView("viewname");
Document doc = null;
doc = vw.getFirstDocument();
while (doc != null) {
// do what you want in here.
doc = vw.getNextDocument(doc);
}
You'll need to make sure you have added the Domino jars to your project. This is a good reference for setting up the eclipse IDE for Domino java development.
PS. You can also modify the design of the database to minimise replication conflicts. But I won't bore you here with the details. Post a comment if you would like to know and ill provide instructions on this thread.
I've created a snippet that pulls data from a databse table and displays it in tabular format. The snippet takes an id as parameter, and this is added to the sql query.
My problem is that if I've got more than 1 snippet call (sometimes need the tabular data for different id's displayed on a page) on the same page, all table data is the same as the last database call that's been made by the last snippet.
What do I need to do to kinda not cache the snippet database calls and have them all display their own content?
I've tried setting the page to no cache-able. Also used the [! !] brackets for the snippet calls, and even used the function_exists() method, but none of them helped.
Please can someone help me?
thanks
Try this at the end of the snippet:
mysql_connect('host', 'user', 'pass');
mysql_select_db('db_name');
You need to specify the connection parameters ofcourse.
It would help to answer if you can post your snippet. I do this with multiple calls on the page without issue, so there is either something wrong inside the snippet, or you need to output to unique placeholder names.
You have encountered a glitch of ModX, and it took me a long time to solve. ModX does a lot of caching by using hashing and apparently, when multiple connections are made from within one page divided over multiple snippets, this erratic behaviour can be seen. This is most likely very unwanted behaviour, it can be solved easily but gives you terrible headache otherways.
One sympton is that $modx->getObject($classname, $id)returns null (often).
The solution is very simple:
either use a static class with a single db instance, or
use $modx->setPlaceholder($instance, $tag);, or a combination.
My solution has been:
class dt__xpdo {
private function __construct() {}
public function __destruct() {
$this->close();
}
static public function db($modx = null) {
if ($modx->getPlaceholder('dt_xpdo') == '') {
$dt_user = 'xxxxxxxxx';
$dt_pw = 'xxxxxxxxx';
$dt_host = 'localhost';
$dt_dbname = 'xxxxxxxxx';
$dt_port = '3306';
$dt_dsn = "mysql:host=$dt_host;dbname=$dt_dbname;port=$dt_port;charset=utf8";
$dt_xpdo = new xPDO($dt_dsn, $dt_user, $dt_pw);
$dt_xpdo->setPackage('mymodel', MODX_CORE_PATH.'components/mymodel/'.'model/', '');
//$modx->log(modX::LOG_LEVEL_DEBUG, 'mymodel.config.php');
//$modx->log(modX::LOG_LEVEL_DEBUG, 'Could not addPackage for mymodel!');
$modx->setPlaceholder('dt_xpdo', $dt_xpdo);
}
return $modx->getPlaceholder('dt_xpdo');
}
}
Now you can use in your code:
require_once 'above.php';
and use something like
$xpdo = dt__xpdo::db($modx);
and continue flawlessly!