There is no statement named UserEntity.insertUser in this SqlMap - mybatis

I am trying to start with mybatis. I did all the configurations but when i want to test the connection to the database i have that error There is no statement named UserEntity.insertUser in this SqlMap.
confif file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- changes from the defaults -->
<setting name="lazyLoadingEnabled" value="false" />
</settings>
<typeAliases>
<typeAlias alias="User" type="com.hosto.Entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/hospidigest"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/hosto/mapper/UserMapper.xml"/>
</mappers>
</configuration>
sql mapper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<sqlMap namespace="com.hosto.dao.UserDao">
<resultMap id="UserResult" class="User">
<result property="lastName" column="LASTNAME"/>
<result property="firstName" column="FIRSTNAME"/>
<result property="password" column="PASSWORD"/>
<result property="email" column="EMAIL"/>
<result property="month" column="MONTH"/>
<result property="day" column="DAY"/>
<result property="year" column="YEAR"/>
<result property="prefixes" column="PREFIXE"/>
<result property="gender" column="GENDER"/>
<result property="personal" column="BASICPERSONNALINFORMATION"/>
</resultMap>
<select id="getAllUsers" resultClass="java.util.ArrayList">
SELECT * FROM user
</select>
<insert id="insertUser" parameterType="com.hosto.Entity.User">
INSERT INTO user (LASTNAME,FIRSTNAME,USERNAME,PASSWORD,EMAIL,MONTH,DAY,YEAR,PREFIXE,GENDER,BASICPERSONNALINFORMATION)
VALUES (#{lastName},#{firstName},#{userName}, #{password}, #{email}, #{month}, #{day}, #{year}, #{prefixes}, #{gender},#{personal})
</insert>
<update id="updateUser" parameterClass="UserDaotest">
UPDATE user SET
LASTNAME= #{lastName},
FIRSTNAME= #{firstName},
USERNAME= #{userName},
PASSWORD= #{password},
EMAIL= #{email},
MONTH= #{month},
DAY= #{day},
YEAR= #{year},
PREFIXE= #{prefixes},
GENDER= #{gender},
BASICPERSONNALINFORMATION= #{personal},
WHERE ID = #{id}
</update>
<delete id="deleteUser" parameterClass="int">
DELETE FROM user where
ID = #{id}
</delete>
<select id="getUserById" resultClass="UserInterface" parameterClass="int">
SELECT *
FROM user
WHERE ID= #{id}
</select>
</sqlMap>
Mybatis Factory
package com.hosto.daoconfig;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public class MyBatisConnectionFactory {
private static SqlSessionFactory sqlSessionFactory;
private static SqlMapClient sqlMapClient = null;
public static SqlMapClient getSqlMapClient() {
try {
String resource = "SqlMapConfig.xml";
Reader reader = Resources.getResourceAsReader(resource);
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
reader.close();
}
catch (IOException iOException) {
iOException.printStackTrace();
}
return sqlMapClient;
}
}
User Dao
package com.hosto.dao;
import java.util.List;
import org.springframework.dao.DataAccessException;
import com.hosto.Entity.User;
/**
* #author Dorian
*
*/
public interface UserDao {
public void insertUser(User user) throws DataAccessException;
public User getUserById(Integer id) throws DataAccessException;
public List<User> getAllUsers()throws DataAccessException;
public void updateUser(User user)throws DataAccessException;
public void deleteUser(Integer userId)throws DataAccessException;
}

It is telling you that it is not defined, you need to create one.
see this for an example here and here

Related

How can I use a variable inside an attribute's value?

How can I use a variable inside an attribute's value?
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.data.mapper.SomeMapper">
<sql id="fields">
<![CDATA[
${alias}some_seq AS `${prefix}someSeq`,
...
]]>
</sql>
<sql id="fieldsAssociative">
<include refid="com.example.demo.data.mapper.SomeMapper.fields">
<property name="alias" value="#{alias}"/> <!-- Can I do this? -->
<property name="prefix" value="#{prefix}"/> <!-- Or this? -->
</include>
,
<include refid="com.example.demo.data.mapper.OtherMapper.fields">
<property name="alias" value="#{alias}2o"/>m
<property name="prefix" value="#{prefix}.otgher."/>
</include>
</sql>
</mapper>

Postgresql result does not match the database using mybatis

config.xml
<mapper namespace="com.###.mapper.EmployeeMapper" >
<resultMap id="EmployeeMap" type="com.###.model.Employee">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="type" property="type"/>
<result column="authority" property="authority"/>
<result column="tel" property="tel"/>
<result column="extra" property="extra"/>
</resultMap>
<select id="getById" parameterType="java.lang.String" resultMap="EmployeeMap" >
SELECT * from employee WHERE id=#{id}
</select>
</mapper>
test code
#Test
void insert() {
// 插入新行
Employee employee = new Employee("", "张三", "教授", null, "13122107768", null);
employeeMapper.insert(employee);
// 查询新行
Assert.assertEquals(employee,employeeMapper.getById(employee.getId()));
}
result
Expected: Employee(id=28, name=张三, type=教授, authority=null, tel=13122107768, extra=null)
Actual: Employee(id=28, name=张三, type=教授, authority=13122107768, tel=13122107768, extra=张三)
I got it! The entity class must have a no-argument constructor

Reusing same ResultMap for two different queries in single fetch in mybatis

Requirement: I need to fetch partial data from two queries and populate the data into single resultmap.
Problem: When we get data from one query it is able to load the data into resultmap, but when I load the data from second query into the same result map the data is getting refreshed.
I guess it is creating a new map when we use same resultmap.Is there a way to make a resultmap available through out the session in mapper.xml.
Code
public Details {
private Term term;
}
public Term {
private String name;
private String location;
}
mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.project.example.MyMapper">
<select id="select_form" parameterType="long" resultMap="select-result">
select id,name from details where id= #{id}
</select>
<select id="select_form_ext" parameterType="long" resultMap="select-result-ext">
select id,location from term where id= #{id}
</select>
<resultMap id="select-result" type="DetailsDto">
<association property="TermDto" column="ID" select="select_form_ext" />
<association property="TermDto" column="ID" resultMap="select-main-result" />
</resultMap>
<resultMap id="select-result-ext" type="TermDto">
<result property="location" column="LOCATION" />
</resultMap>
<resultMap id="select-main-result" type="TermDto" >
<result property="name" column="NAME" />
</resultMap>
</mapper>
Please give a try using the below steps.
Step1#: Remove the below line <association property="TermDto" column="ID" resultMap="select-main-result" /> from <resultMap id="select-result" >...
Step2#: Modify the ResultMapselect-result-ext as below
<resultMap id="select-result-ext" type="TermDto">
<result property="location" column="LOCATION" />
<result property="name" column="NAME" />
</resultMap>
Step3#: Execute/Run the application and check the Results.
Eg#:
<resultMap id="blogResult" type="Blog">
<association property="author" column="author_id" javaType="Author" select="selectAuthor"/>
</resultMap>
<select id="selectBlog" resultMap="blogResult">
SELECT * FROM BLOG WHERE ID = #{id}
</select>
<select id="selectAuthor" resultType="Author">
SELECT * FROM AUTHOR WHERE ID = #{id}
</select>

Tomcat + Eclipse Link + Vaadin, NoClassDefFoundError javax/persistence/Persistence

I'm using Vaadin and Eclipse Link for my web application based on MySQL database.
I have a following class to manage db operations:
public class DatabaseManager {
private static final String PERSISTENCE_UNIT_NAME = "students";
private static EntityManagerFactory factory;
private static EntityManager em;
public DatabaseManager() {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
em = factory.createEntityManager();
}
public void addEntry(Student student) {
em.getTransaction().begin();
em.persist(student);
em.getTransaction().commit();
}
}
and the following persistence.xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="students" transaction-type="RESOURCE_LOCAL">
<class>com.example.simplegradebook.Student</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:derby:C:\\Users\\Ja\\workspace\\SimpleDB;create=true" />
<property name="javax.persistence.jdbc.user" value="test" />
<property name="javax.persistence.jdbc.password" value="test" />
<!-- EclipseLink should create the database schema automatically -->
<!-- <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> -->
<property name="eclipselink.ddl-generation.output-mode" value="both" />
</properties>
I also have a DBTest class in which I test DatabaseManager in console and everything seems to be okay. But when I put for example:
DatabaseManager dbm = new DatabaseManager();
dbm.addEntry(new Student(/*some stuff here*/));
in my VaadinUI class, I get errors like that:
com.vaadin.server.ServiceException: java.lang.NoClassDefFoundError: javax/persistence/Persistence
com.vaadin.server.VaadinService.handleExceptionDuringRequest(VaadinService.java:1463)
com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1417)
com.vaadin.server.VaadinServlet.service(VaadinServlet.java:237)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
java.lang.NoClassDefFoundError: javax/persistence/Persistence
com.example.simplegradebook.DatabaseManager.<init>(DatabaseManager.java:19)
com.example.simplegradebook.SimplegradebookUI.init(SimplegradebookUI.java:44)
com.vaadin.ui.UI.doInit(UI.java:641)
com.vaadin.server.communication.UIInitHandler.getBrowserDetailsUI(UIInitHandler.java:222)
com.vaadin.server.communication.UIInitHandler.synchronizedHandleRequest(UIInitHandler.java:74)
com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1405)
com.vaadin.server.VaadinServlet.service(VaadinServlet.java:237)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
I have these libraries included in my project:
javax.persistence_2.1.0.v201304241213.jar
javax.persistence.source_2.1.0.v201304241213.jar
Any ideas what may cause the problem?

OpenJPA orphan removal not working

I am trying out a master child test case with a OneToMany unidirectional relationship.
I have a scenario where I want to update the master by removing some entries from the children list. When I do a merge, I want these child entries to be automatically deleted.
I have tried in vain to get this working. I tried orphanremoval too, but that too didn't help. There were some suggestions to add equals and hashcode, which didn't work either.
Any hint or help in this regard is highly appreciated. Thank you.
I am using JPA2.0 with OpenJPA 2.1.0
Here is my code.
//Parent class
public class Account {
private String accountId;
private String accountNumber;
private List<SubAccount> subAccounts;
//followed by getters/setters
}
//Child class
public class SubAccount {
private String subAccountId;
private String subAccountNumber;
//followed by getters/setters
}
My orm.xml is as follows.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<entity-mappings version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd">
<entity name="Account" class="test.data.Account">
<table name="ACCOUNT" />
<sequence-generator name="AccountSeq"
sequence-name="ACCOUNT_TEST_SEQ" />
<attributes>
<id name="accountId">
<column name="ACCOUNT_ID" />
<generated-value strategy="SEQUENCE" generator="AccountSeq" />
</id>
<basic name="accountNumber">
<column name="ACCOUNT_NO" />
</basic>
<one-to-many name="subAccounts" fetch="EAGER"
target-entity="test.data.SubAccount" orphan-removal="true" >
<join-column name="ACCOUNT_ID" referenced-column-name="ACCOUNT_ID" nullable="false" updatable="true"/>
<cascade>
<cascade-all />
</cascade>
</one-to-many>
</attributes>
</entity>
<entity name="SubAccount" class="test.data.SubAccount">
<table name="SUBACCOUNT" />
<sequence-generator name="SubAccountSeq"
sequence-name="SUBACCOUNT_TEST_SEQ" />
<attributes>
<id name="subAccountPK">
<column name="SUBACCOUNT_ID" />
<generated-value strategy="SEQUENCE" generator="AccountSeq" />
</id>
<basic name="subAccountNumber">
<column name="SUBACCOUNT_NO" />
</basic>
</attributes>
</entity>
</entity-mappings>
And this is what I am trying to do.
Account acc = (Account)entityMgr.find(Account.class, "1100")
acc.getSubAccounts().remove(0);
entityMgr.merge(acc)
I expect the subaccount to be deleted.
OpenJPA overrides the orphan-removal behavior if the cascade type is set to cascade-all or cascade-remove.
Instead of cascade-all, I had to configure cascade-type with cascade-persist, cascade-merge, cascade-refresh and cascade-detach.