;相关下载

https://www.qxorm.com/qxorm_en/download.html

;QxModels.h


#include "precompiled.h"
/***************************************************************
* @projectName pluqt
* @brief 自定义ORM模型
* @author lzw
* @date 2022-01-04
***************************************************************/
struct User
{
long id;
QString name;
int age;
QString hobbies;
};
QX_REGISTER_HPP_QX_DLL1(User, qx::trait::no_base_class_defined, 1)

 

源文件:QxModels.cpp

 #include "precompiled.h"
#include "qxmodels.h"
#include <QxOrm_Impl.h>
QX_REGISTER_CPP_QX_DLL1(User)
namespace qx
{
    template <> void register_class(QxClass<User> & t)
    {
        // 设置表名
        t.setName("User");
        // 注册 User::id <=> 数据库中的主键
        t.id(&User::id, "id");
        // 注册 User::name 属性,使用的 key 是 name,version 是 1。
        t.data(&User::name, "name", 1);
        // 注册 User::age 属性,使用的 key 是 age。
        t.data(&User::age, "age");
        // 注册 User::hobbies 属性,使用的 key 是 hobbies。
        t.data(&User::hobbies, "hobbies");
    }
}
 
; 连接数据库。
QString in_db = QCoreApplication::applicationDirPath();
   in_db.append("/database/plulocal.db");
   QFile::remove(in_db);
   qx::QxSqlDatabase::getSingleton()->setDriverName("QSQLITE");
   qx::QxSqlDatabase::getSingleton()->setDatabaseName(in_db);
   qx::QxSqlDatabase::getSingleton()->setHostName("localhost");
   qx::QxSqlDatabase::getSingleton()->setUserName("root");
   qx::QxSqlDatabase::getSingleton()->setPassword("");
   qx::QxSqlDatabase::getSingleton()->setSqlPlaceHolderStyle(qx::QxSqlDatabase::ph_style_2_point_name);
   qx::QxSqlDatabase::getSingleton()->setTraceSqlQuery(true);
   qx::QxSqlDatabase::getSingleton()->setTraceSqlRecord(false);
;使用ORM。建表,新增,简单查询,复杂查询等等
// 建表
    QSqlError daoError1 = qx::dao::create_table<User>();
    // 产生100条模拟数据
    for(int in_idx=0; in_idx<100; ++in_idx)
    {
        auto in_user = new User();
        in_user->name = "lzw"+QString::number(in_idx);
        in_user->age = 20+in_idx;
        in_user->hobbies = "play";
        auto daoError1 = qx::dao::insert(in_user);
    }
    // 查询单条记录
    User in_pointUser; in_pointUser.id = 3;
    qDebug()<<in_pointUser.name;
    QSqlError daoError11 = qx::dao::fetch_by_id(in_pointUser);
    qDebug()<<in_pointUser.name;
    // 查询一定年龄段的集合记录
    //typedef std::shared_ptr<User> UserPtr;
    //typedef qx::QxCollection<long, UserPtr> UserList;
    UserList in_userList;
    qx_query in_query("select * from user where age>=20 and age<=25");
    daoError11 = qx::dao::execute_query(in_query, in_userList);
    qAssert(! daoError11.isValid()); qAssert(in_userList.count() > 0);
    qx::dump(in_userList);

;序列化的两个函数

// 导出binary流

    qx::serialization::qt::to_file(in_pointUser, "user.txt");
    // 导出json文本
    qx::serialization::json::to_file(in_userList, "list_of_user.json");

;过滤sql打印

https://www.zhihu.com/people/qi-hong-tao-30-81

https://www.ljjyy.com/archives/2023/05/100647

运行程序,会打印一系列sql执行的输出信息,QxOrm 不会隐藏 SQL 查询(默认情况下,所有的语句都会显示),所以在控制台中可以看到执行过程,如果想要关闭,可以使用官方建议的下面的方法,但是我测试了没有用,因此我用QT的自定义日志拦截器对 包含 QxOrm的日志进行了过滤。

 

    qx::QxSqlDatabase::getSingleton()->setFormatSqlQueryBeforeLogging(false);

    qx::QxSqlDatabase::getSingleton()->setVerifyOffsetRelation(false);

    qx::QxSqlDatabase::getSingleton()->setTraceSqlQuery(false);

    qx::QxSqlDatabase::getSingleton()->setTraceSqlBoundValuesOnError(false);

    qx::QxSqlDatabase::getSingleton()->setTraceSqlRecord(false);

    qx::QxSqlDatabase::getSingleton()->setTraceSqlBoundValues(false);

    qx::QxSqlDatabase::getSingleton()->setTraceSqlBoundValuesOnError(false);

 

 ;自定义导出

https://www.cnblogs.com/chinasoft/p/16065959.html

https://www.qxorm.com/qxorm_en/manual_qxee.html

复制第一个的h和cpp到custom里面,增加 一下两个include 

#include <models_export.gen.h>
#include <models_precompiled_header.gen.h>

 ;预览c++代码

 pimpl不要勾选,会增加编译时间

 ;完整代码

int main(int argc, char * argv[])
{
   // Qt application
   QCoreApplication app(argc, argv);
   QFile::remove("./qxBlog.sqlite");

   // Parameters to connect to database
   qx::QxSqlDatabase::getSingleton()->setDriverName("QSQLITE");
   qx::QxSqlDatabase::getSingleton()->setDatabaseName("./qxBlog.sqlite");
   qx::QxSqlDatabase::getSingleton()->setHostName("localhost");
   qx::QxSqlDatabase::getSingleton()->setUserName("root");
   qx::QxSqlDatabase::getSingleton()->setPassword("");

   // Only for debug purpose : assert if invalid offset detected fetching a relation
   qx::QxSqlDatabase::getSingleton()->setVerifyOffsetRelation(true);

   // !!! TO CREATE TABLES, PLEASE USE THE C++ DDL SQL EXPORT PLUGIN OF QXENTITYEDITOR !!!
   // Create all tables in database (you should not use 'qx::dao::create_table<T>()' function in a production software, use it just for prototypes or samples)
   QSqlError daoError = qx::dao::create_table<author>();
   daoError = qx::dao::create_table<comment>();
   daoError = qx::dao::create_table<category>();
   daoError = qx::dao::create_table<blog>();

   // Create a list of 3 author
   author_ptr author_1; author_1.reset(new author());
   author_ptr author_2; author_2.reset(new author());
   author_ptr author_3; author_3.reset(new author());

   author_1->setlastname("author_1");
   author_1->setsex(sex::male);
   author_1->setbirthdate(QDateTime::currentDateTime());
   author_2->setlastname("author_2");
   author_2->setsex(sex::female);
   author_2->setbirthdate(QDateTime::currentDateTime());
   author_3->setlastname("author_3");
   author_3->setsex(sex::female);
   author_3->setbirthdate(QDateTime::currentDateTime());

   list_of_author authorX;
   authorX.insert(1, author_1);
   authorX.insert(2, author_2);
   authorX.insert(3, author_3);

   // Insert list of 3 author into database
   daoError = qx::dao::insert(authorX);
   qAssert(qx::dao::count<author>() == 3);

   // Clone author n°2 : 'author_id_2'
   author_ptr author_clone = qx::clone(* author_2);
   qAssert(author_clone->getauthor_id() == author_2->getauthor_id());
   qAssert(author_clone->getsex() == sex::female);

   // Create a query to fetch only female author : 'author_id_2' and 'author_id_3'
   qx::QxSqlQuery query("WHERE t_author.sex = :sex");
   query.bind(":sex", sex::female);

   list_of_author list_of_female_author;
   daoError = qx::dao::fetch_by_query(query, list_of_female_author);
   qAssert(list_of_female_author.count() == 2);

   // Dump list of female author (xml serialization)
   qx::dump(list_of_female_author);

   // Create 3 categories
   category_ptr category_1 = category_ptr(new category("cat_1"));
   category_ptr category_2 = category_ptr(new category("cat_2"));
   category_ptr category_3 = category_ptr(new category("cat_3"));

   category_1->setname("category_1"); category_1->setdescription("desc_1");
   category_2->setname("category_2"); category_2->setdescription("desc_2");
   category_3->setname("category_3"); category_3->setdescription("desc_3");

   { // Create a scope to destroy temporary connexion to database

   // Open a transaction to database
   QSqlDatabase db = qx::QxSqlDatabase::getDatabase();
   bool bCommit = db.transaction();

   // Insert 3 categories into database, use 'db' parameter for the transaction
   daoError = qx::dao::insert(category_1, (& db));    bCommit = (bCommit && ! daoError.isValid());
   daoError = qx::dao::insert(category_2, (& db));    bCommit = (bCommit && ! daoError.isValid());
   daoError = qx::dao::insert(category_3, (& db));    bCommit = (bCommit && ! daoError.isValid());

   qAssert(bCommit);
   qAssert(category_1->getcategory_id() != "");
   qAssert(category_2->getcategory_id() != "");
   qAssert(category_3->getcategory_id() != "");

   // Terminate transaction => commit or rollback if there is error
   if (bCommit) { db.commit(); }
   else { db.rollback(); }

   } // End of scope : 'db' is destroyed

   // Create a blog with the class name (factory)
   boost::any blog_any = qx::create("blog");
   blog_ptr blog_1;
   try { blog_1 = boost::any_cast<blog_ptr>(blog_any); }
   catch (...) { blog_1.reset(new blog()); }
   blog_1->settext("blog_text_1");
   blog_1->settitle("blog_title_1");
   blog_1->setauthor(author_1);

   // Insert 'blog_1' into database with 'save()' method
   daoError = qx::dao::save(blog_1);

   // Modify 'blog_1' properties and save into database
   blog_1->settext("update blog_text_1");
   blog_1->setauthor(author_2);
   daoError = qx::dao::save(blog_1);

   // Add 2 comments to 'blog_1'
   comment_ptr comment_1; comment_1.reset(new comment());
   comment_ptr comment_2; comment_2.reset(new comment());

   comment_1->settext("comment_1 text");
   comment_1->setblog_id(blog_1);
   comment_2->settext("comment_2 text");
   comment_2->setblog_id(blog_1);

   daoError = qx::dao::insert(comment_1);
   daoError = qx::dao::insert(comment_2);
   qAssert(qx::dao::count<comment>() == 2);

   // Add 2 categories to 'blog_1' => must insert into extra-table 'category_blog'
   blog::type_list_of_category lst_category;
   lst_category.insert(category_1->getcategory_id(), category_1);
   lst_category.insert(category_3->getcategory_id(), category_3);
   blog_1->setlist_of_category(lst_category);
   daoError = qx::dao::save_with_relation("list_of_category", blog_1);

   // Fetch blog into a new variable with all relation : 'author', 'comment' and 'category'
   blog_ptr blog_tmp; blog_tmp.reset(new blog());
   blog_tmp->setblog_id(blog_1->getblog_id());
   daoError = qx::dao::fetch_by_id_with_all_relation(blog_tmp);

   qAssert(blog_tmp->list_of_comment().count() == 2);
   qAssert(blog_tmp->list_of_category().count() == 2);
   qAssert(blog_tmp->gettext() == "update blog_text_1");
   qAssert(blog_tmp->getauthor() && blog_tmp->getauthor()->getauthor_id() == author_2->getauthor_id());

   // Fetch blog into a new variable with many relations using "*->*->*->*" (4 levels of relationships)
   blog_tmp.reset(new blog());
   blog_tmp->setblog_id(blog_1->getblog_id());
   daoError = qx::dao::fetch_by_id_with_relation("*->*->*->*", blog_tmp);

   qAssert(blog_tmp->list_of_comment().count() == 2);
   qAssert(blog_tmp->list_of_category().count() == 2);
   qAssert(blog_tmp->gettext() == "update blog_text_1");
   qAssert(blog_tmp->getauthor() && blog_tmp->getauthor()->getauthor_id() == author_2->getauthor_id());

   // Dump 'blog_tmp' result from database (xml serialization)
   qx::dump(blog_tmp);

   // Check qx::dao::save_with_relation_recursive() function
   daoError = qx::dao::save_with_relation_recursive(blog_tmp);
   qAssert(! daoError.isValid());
   daoError = qx::dao::save_with_relation_recursive(blog_tmp, qx::dao::save_mode::e_update_only);
   qAssert(! daoError.isValid());

   // Call 'age()' method with class name and method name (reflexion)
   //qx_bool bInvokeOk = qx::QxClassX::invoke("author", "age", author_1);
   //qAssert(bInvokeOk);

   // Test 'isDirty()' method
   qx::dao::ptr<blog> blog_isdirty = qx::dao::ptr<blog>(new blog());
   blog_isdirty->setblog_id(blog_1->getblog_id());
   daoError = qx::dao::fetch_by_id(blog_isdirty);
   qAssert(! daoError.isValid() && ! blog_isdirty.isDirty());

   blog_isdirty->settext("blog property 'text' modified => blog is dirty !!!");
   QStringList lstDiff; bool bDirty = blog_isdirty.isDirty(lstDiff);
   qAssert(bDirty && (lstDiff.count() == 1) && (lstDiff.at(0) == "text"));
   if (bDirty) { qDebug("[QxOrm] test dirty 1 : blog is dirty => '%s'", qPrintable(lstDiff.join("|"))); }

   // Update only property 'm_text' of 'blog_isdirty'
   daoError = qx::dao::update_optimized(blog_isdirty);
   qAssert(! daoError.isValid() && ! blog_isdirty.isDirty());
   qx::dump(blog_isdirty);

   // Test 'isDirty()' method with a container
   typedef qx::dao::ptr< QList<author_ptr> > type_lst_author_test_is_dirty;
   type_lst_author_test_is_dirty container_isdirty = type_lst_author_test_is_dirty(new QList<author_ptr>());
   daoError = qx::dao::fetch_all(container_isdirty);
   qAssert(! daoError.isValid() && ! container_isdirty.isDirty() && (container_isdirty->count() == 3));

   author_ptr author_ptr_dirty = container_isdirty->at(1);
   author_ptr_dirty->setlastname("author name modified at index 1 => container is dirty !!!");
   bDirty = container_isdirty.isDirty(lstDiff);
   qAssert(bDirty && (lstDiff.count() == 1));
   if (bDirty) { qDebug("[QxOrm] test dirty 2 : container is dirty => '%s'", qPrintable(lstDiff.join("|"))); }

   author_ptr_dirty = container_isdirty->at(2);
   author_ptr_dirty->setfirstname("firstname changed");
   bDirty = container_isdirty.isDirty(lstDiff);
   qAssert(bDirty && (lstDiff.count() == 2));
   if (bDirty) { qDebug("[QxOrm] test dirty 3 : container is dirty => '%s'", qPrintable(lstDiff.join("|"))); }

   // Update only property 'm_name' at position 1, only property 'm_birthdate' at position 2 and nothing at position 0
   daoError = qx::dao::update_optimized(container_isdirty);
   qAssert(! daoError.isValid() && ! container_isdirty.isDirty());
   qx::dump(container_isdirty);

   // Fetch only property 'm_text' of blog
   QStringList lstColumns = QStringList() << "text";
   QList<blog_ptr> lst_blog_with_only_text;
   daoError = qx::dao::fetch_all(lst_blog_with_only_text, NULL, lstColumns);
   qAssert(! daoError.isValid() && (lst_blog_with_only_text.size() > 0));
   if ((lst_blog_with_only_text.size() > 0) && (lst_blog_with_only_text[0].get() != NULL))
   { qAssert(lst_blog_with_only_text[0]->gettitle().isEmpty()); }
   qx::dump(lst_blog_with_only_text);

   // Dump all registered classes into QxOrm context (introspection engine)
   qx::QxClassX::dumpAllClasses();

   // Call a custom SQL query or a stored procedure
   qx_query testStoredProc("SELECT * FROM t_author");
   daoError = qx::dao::call_query(testStoredProc);
   qAssert(! daoError.isValid());
   testStoredProc.dumpSqlResult();

   // Call a custom SQL query or a stored procedure and fetch automatically properties (with a collection of items)
   qx_query testStoredProcBis("SELECT * FROM t_author");
   authorX.clear();
   daoError = qx::dao::execute_query(testStoredProcBis, authorX);
   qAssert(! daoError.isValid()); qAssert(authorX.count() > 0);
   qx::dump(authorX);

   // Call a custom SQL query or a stored procedure and fetch automatically properties
   qx_query testStoredProcThird("SELECT name, category_id FROM t_category");
   category_ptr category_tmp = category_ptr(new category());
   daoError = qx::dao::execute_query(testStoredProcThird, category_tmp);
   qAssert(! daoError.isValid()); qAssert(category_tmp->getcategory_id() != "");
   qx::dump(category_tmp);

   return 0;
}

运行程序,会打印一系列sql执行的输出信息,QxOrm 不会隐藏 SQL 查询(默认情况下,所有的语句都会显示),所以在控制台中可以看到执行过程,如果想要关闭,可以使用官方建议的下面的方法,但是我测试了没有用,因此我用QT的自定义日志拦截器对 包含 QxOrm的日志进行了过滤。

    qx::QxSqlDatabase::getSingleton()->setFormatSqlQueryBeforeLogging(false);
    qx::QxSqlDatabase::getSingleton()->setVerifyOffsetRelation(false);
    qx::QxSqlDatabase::getSingleton()->setTraceSqlQuery(false);
    qx::QxSqlDatabase::getSingleton()->setTraceSqlBoundValuesOnError(false);
    qx::QxSqlDatabase::getSingleton()->setTraceSqlRecord(false);
    qx::QxSqlDatabase::getSingleton()->setTraceSqlBoundValues(false);
    qx::QxSqlDatabase::getSingleton()->setTraceSqlBoundValuesOnError(false);
posted on 2024-01-26 10:26  jk0011  阅读(13)  评论(0编辑  收藏  举报