Project

General

Profile

Wt::Dbo id() always return 0

Added by Alexandre Lavoie about 1 year ago

I have an object :

class CustomObject;

namespace Wt
{
    namespace Dbo
    {
        template<>
        struct dbo_traits<RFNode> : public dbo_default_traits
        {
            static const char *versionField() { return 0; }
        };
    }
}

class CustomObject : public Wt::Dbo::Dbo<long long>
{
    public:
        CustomObject(void)
        {
            m_nID   = -1;
            m_sName = "";
        }

        CustomObject(std::string p_sName)
        {
            m_nID   = -1;
            m_sName = p_sName;
        }

        CustomObject(CustomObject *p_pOriginal)
        {
            m_nID   = p_pOriginal->getID();
            m_sName = p_pOriginal->getName();
        }

        ~CustomObject(void)
        {

        }

        void setID(int p_nID)
        {
            m_nID = p_nID;
        }

        int getID(void)
        {
            if(m_nID == -1)
            {
                return id();
            }
            else
            {
                return m_nID;
            }
        }

        void setName(std::string p_sName)
        {
            m_sName = p_sName;
        }

        std::string getName(void)
        {
            return m_sName;
        }

        template<class Action>
        void persist(Action &a)
        {
            Wt::Dbo::field(a,m_sName,"name");
        };

    private:
        int m_nID;
        std::string m_sName;
};

When I load it from the database, and call getID() or id(), the result is always 0, the object exist in database and the attributes are loaded properly. I'm probably doing something wrong but not found yet. I've also tried using a natural key which is working but since there is no way to activate the auto-increment, the inserts doesn't work.

Thank you!


Replies (2)

RE: Wt::Dbo id() always return 0 - Added by alisa jorez 12 months ago

Well i think It appears that the problem is due to how you use the Wt::Dbo library to load the object from the database.
Check that the main key column in the database table is auto-incrementing: The id() method of the Wt::Dbo::Dbo base class returns the value of the object's main key field. If the main key field is not auto-incremented, a newly formed object's id() function will return 0. Check that your database table's primary key field is set to auto-increment.

RE: Wt::Dbo id() always return 0 - Added by Roel Standaert 12 months ago

class CustomObject : public Wt::Dbo::Dbo<long long>

That's an odd line. Wt::Dbo::Dbo uses the curiously recurring template pattern (CRTP). You're supposed to use it like this:

class CustomObject : public Wt::Dbo::Dbo<CustomObject>

    (1-2/2)