I am creating a ShoppingCart App using Spring-mvc.In dao layer I am using Spring-Hibernate ORM feature.
#Repository("baseDao")
public class BaseDaoImpl<T extends ShoppingCartEntity> implements BaseDao<T>
{
#Autowired
protected SessionFactory sessionFactory;
private Class<T> entityClass;
public BaseDaoImpl(Class<T> entityClass) {
super();
this.entityClass = entityClass;
}
public Serializable save(T entity) {
return sessionFactory.getCurrentSession().save(entity);
}
public void update(T entity) {
sessionFactory.getCurrentSession().update(entity);
}
public void saveOrUpdate(T entity) {
sessionFactory.getCurrentSession().saveOrUpdate(entity);
}
}
CartDaoImpl.java
#Repository("cartDao")
public class CartDaoImpl extends BaseDaoImpl<CartMaster> implements CartDao {
private Class<CartMaster> entityClass;
public CartDaoImpl(#Value("com.orgn.shc.entity.CartMaster")Class<CartMaster> entityClass) {
super(entityClass);
this.entityClass = entityClass;
}
//other getter & setter
}
I have a base entity class named ShoppingCartEntity.java.
#MappedSuperclass
public class ShoppingCartEntity implements Serializable {
private static final long serialVersionUID = 1L;
//other fields
}
CartMaster.java:
#Entity
#Table(name = "SHOP_CART_MASTER")
public class CartMaster extends ShoppingCartEntity {
//other fields
}
Now,during deployment of application in weblogic I am getting following exception:
<28 Dec, 2017, 11:48:08,916 PM IST> <Error>
<org.springframework.web.servlet.DispatcherServlet> <BEA-000000> <Context
initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'baseDao' defined in URL [zip:C:/Oracle
/Middleware/ORACLE_HOME/user_projects/domains/wl_server/servers
/AdminServer/tmp/_WL_user/shoppingcart/8i2b70/war/WEB-INF/lib
/wl_cls_gen.jar!/com/orgn/shc/dao/impl/BaseDaoImpl.class]: Unsatisfied
dependency expressed through constructor parameter 0; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'java.lang.Class<?>' available: expected at least
1 bean which qualifies as autowire candidate. Dependency annotations: {}
at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
Its spring-bean configuraation part as below
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/SHPDS"
expected-type="javax.sql.DataSource" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.orgn.shc.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
</props>
</property>
</bean>
<mvc:annotation-driven />
<context:component-scan base-package="com.orgn.shc" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/assets/**" location="/assets/" />
My perception is that #Value annotation at constructor level is sufficient to inject the dependencies accordingly in sub classes.
Can anyone has any suitable solution to this?
Remove #Repository("baseDao") from your BaseDaoImpl as it should not be created as a separate bean; instead, it should be only used as a parent for other DAO classes. I would also make it abstract and its constructor protected to avoid accidental instantiation.
Also, it looks like you need to change the constructor of your CartDaoImpl to the following:
public CartDaoImpl() {
super(CartMaster.class);
}
And I don't believe you actually need entityClass field in CartDaoImpl as you know the class of your entity in this DAO: it's CartMaster.class. At the same time, in BaseDaoImpl that entityClass field may be useful to read entities from database (even though you don't have such methods).
Related
I am trying to make a simple Spring MVC application using Spring Data, hibernate and H2 database. But spring cannot find the repository as a bean.
The error when application start:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'taskService': Unsatisfied dependency expressed through method 'setTaskRepository' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.spring.intership.repositories.TaskRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.spring.intership.repositories.TaskRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
TaskRepository.java
#Repository
public interface TaskRepository extends JpaRepository<Task, Long> {
}
TaskSerice.java
public interface TaskService {
public List<Task> getAll();
public void save(Task t);
}
TaskServiceImpl.java
public class TaskServiceImpl implements TaskService {
private TaskRepository taskRepository;
#Override
public void add(Task task) {
taskRepository.save(task);
}
#Override
public List<Task> getAll() {
LinkedList<Task> tasks = new LinkedList<>();
taskRepository.findAll().forEach(tasks::add);
return tasks;
}
#Autowired
public void setTaskRepository(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
}
BeanConfiguration.java
#Configuration
public class BeanConfiguration {
#Bean
MemoryService memoryService() {
return new MemoryServiceImpl();
}
#Bean
TimeService timeService() {
return new TimeServiceImpl();
}
#Bean
NameService nameService() {
return new NameServiceImpl();
}
#Bean
TaskService taskService() {return new TaskServiceImpl(); }
}
application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.springframework.jdbc.datasource.SimpleDriverDataSource" id="dataSource">
<property name="driverClass" value="${db.driverClass}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.spring.intership.entities" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.driver_class">org.h2.Drive</prop>
</props>
</property>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer"
init-method="start" destroy-method="stop">
<constructor-arg value="-web,-webAllowOthers,-webDaemon,-webPort,8082" />
</bean>
<jpa:repositories base-package="com.spring.intership.repositories"/>
</beans>
And i have this in my web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/config/application-context.xml
WEB-INF/config/application.properties
</param-value>
</context-param>
I have very little experience in MVC spring (a little more in boot) so please consider the most obvious mistakes too;
P.S. My Task.java
#Entity
#Transactional
public class Task {
private long number;
private String description;
private Date date;
#Id
#Column(name = "ID")
public long getNumber()
{
return number;
}
#Basic
#Column(name = "DESCRIPTION")
public String getDescription()
{
return description;
}
#Basic
#Column(name = "DATE")
public Date getDate()
{
return date;
}
public void setNumber(long number)
{
this.number = number;
}
public void setDate(Date date) {
this.date = date;
}
public void setDescription(String description) {
this.description = description;
}
}
try this tips:
Use "#ComponentScan" annotation in "BeanConfiguration" class. Note that you can use "#ComponentScan(basePackages = "com.example.package")" to force scan of the package when your repositories are.
You can use "#EnableJpaRepository(basePackages = "package.of.repositories")" to scan specific package to find ONLY repositories.
Let's check if "Task" class is annoted with "#Entity"
Consider to convert you context to class and try to use annotation instead of xml bean definition.
If you choose to use #ComponentScan annotation consider to scan all packages' tree. If your packages are "com.example.repository", "com.example.controller", "com.example.service" let's scan "com.example" in order to scan also future packages' you will add
I agree with #Luke.
Also you should autowire TaskRepository in TaskService.
public class TaskServiceImpl implements TaskService {
#Autowired
private TaskRepository taskRepository;
....
I'm unit testing my Hibernate DAO layer with jUnit4 and Mockito and I'm having problems mocking get(Class<T> entityType, Serializable id).
I have no errors along the way, the only thing is that my assertion fails as actualAddress is null.
// imports here
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "classpath:applicationContext.xml")
public class AddressDAOImplTest {
#Autowired
#InjectMocks
private AddressDAO addressDAO;
#Mock
private SessionFactory sessionFactory;
#Mock
private Session session;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void getAddress() {
Address expectedAddress = getTestAddress(1);
Mockito
.doReturn(session)
.when(sessionFactory)
.openSession();
Mockito
.doReturn(expectedAddress)
.when(session)
.get(Matchers.eq(Address.class), Matchers.anyInt()); // doesn't match
Mockito
.doNothing()
.when(session)
.close();
Address actualAddress = addressDAO.getAddress(1);
Assert.assertEquals(expectedAddress, actualAddress);
}
}
somewhere AddressDAOImpl:
public Address getAddress(Integer id) {
Session session = sessionFactory.openSession();
Address address = null;
try {
address = session.get(Address.class, id); // returns null as it can't match the mocked method
} catch (Exception e) {
// some logging here :)
} finally {
session.close();
return address;
}
}
SessionFactory setup:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.webservices.models"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.apache.tomcat.dbcp.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
Hibernate props:
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:orders;DB_CLOSE_DELAY=-1
jdbc.username=
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=create-drop
hibernate.show_sql=true
To my understanding get(Matchers.eq(Address.class), Matchers.anyInt()) doesn't match the actual method, which leads to null as a return value.
I'd greatly appreciate your help!
I am using Spring-ORM to add a Employee* object in Table called emp using HibernateTemplate.
But when I'm trying to execute the program I'm getting this error:
Error creating bean with name 'testBean': Unsatisfied dependency expressed through field 'dao'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:E rror creating bean with name 'empDaoImpl': Unsatisfied dependency expressed through field 'ht'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ht' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is
org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [alter table emp add empno number(10,0) not null]
This is My java bean
#Service
public class TestBean
{
#Autowired
private EmpDao dao;
public void persistEmp(int empid,String empName,int sal,int deptno)
{
Employee e=new Employee();
e.setEmpid(empid);
e.setEmpName(empName);
e.setEmpSalary(sal);
e.setDeptNum(deptno);
dao.save(e);
}
public void updateEmp(int empid,String empName,int sal,int deptno)
{
Employee e=new Employee();
e.setEmpid(empid);
e.setEmpName(empName);
e.setEmpSalary(sal);
e.setDeptNum(deptno);
dao.update(e);
}
public void deleteEmp(int empid)
{
dao.deleteEmployee(empid);
}
public void selectEmps()
{
List lt=dao.selectEmployees();
Iterator it=lt.iterator();
while(it.hasNext())
{
Employee e1=(Employee)it.next();
System.out.println(e1);
}
}
}
*This is my Entity class
#Entity
#Table(name="emp")
public class Employee
{
#Id
#Column(name="empno")
private int empid;
#Column(name="ename")
private String empName;
#Column(name="sal")
private int empSalary;
#Column(name="deptno")
private int deptNum;
//Setters and Getters
public String toString()
{
return "Employee["+empid+" "+empName+" "+empSalary+" "+deptNum+"]";
}
}
This is my EmpDaoImpl class
#Repository
#Transactional
public class EmpDaoImpl implements EmpDao
{
#Autowired
private HibernateTemplate ht;
public void deleteEmployee(int empid)
{
Employee e=(Employee)ht.get(Employee.class, empid);
ht.delete(e);
System.out.println("one Employee object is deleted");
}
public List selectEmployees()
{
List empList=ht.find("from Employee e");
return empList;
}
public void save(Employee e)
{
ht.save(e);
System.out.println("Object is saved ");
}
public void update(Employee e)
{
ht.update(e);
System.out.println("Object is Updated");
}
}
This is my Main class
public class Main
{
public static void main(String[] args)
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
TestBean testB=(TestBean)ctx.getBean("testBean");
testB.persistEmp(7999, "naveen", 55555, 40);
System.out.println("===============================");
}
}
This is my applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.pack1"></context:component-scan>
<bean id="ht" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="ds"></property>
<property name="annotatedClasses">
<list>
<value>com.pack1.entity.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
</value>
</property>
</bean>
<bean id="txm" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="tiger"/>
</bean>
<tx:annotation-driven transaction-manager="txm"/>
</beans>
When hibernate.hbm2ddl.auto is set to update Hibernate won't modify existing table column definitions. So, you can manually alter the column definition or drop the table/column and run your code. In the latter case, hibernate will create the column if it is not present.
Please refer here, here and here for more info on hibernate.hbm2ddl.auto options and how they work.
[enter image description here][1]
Account.java
package com.hibernateWithSpring;
public class Account {
private int accountNumber;
private String owner;
private double balance;
public Account(){
}
public Account(int accountNumber, String owner, double balance) {
this.accountNumber=accountNumber;
this.owner= owner;
this.balance=balance;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
AccountClient.java
package com.hibernateWithSpring;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class AccountClient {
public static void main(String[] args){
ApplicationContext context=new FileSystemXmlApplicationContext("bin/beans.xml");
AccountDao accountdao = context.getBean("accountDaoBean",AccountDao.class);
accountdao.createAccount(110, "varun",1000);
accountdao.createAccount(111, "vicky",1200);
System.out.println("account created");
accountdao.updateBalance(111,2222);
System.out.println("account updated");
accountdao.deleteAccount(111);
System.out.println("account deleted");
List<Account> account= accountdao.getAllAccount();
for(int i=0;i<account.size();i++){
Account acc=account.get(i);
System.out.println(acc.getAccountNumber()+":"+acc.getOwner()+":"+acc.getBalance());
}
}
}
AccountDao.java
package com.hibernateWithSpring;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class AccountDao extends HibernateDaoSupport
{
public void createAccount(int accountNumbeer, String owner, double balane){
Account account= new Account(accountNumbeer,owner,balane);
getHibernateTemplate().save(account);
}
public void updateBalance(int accountNumber, double newBalance){
Account account= getHibernateTemplate().get(Account.class, accountNumber);
if(account !=null){
account.setBalance(newBalance);
}
getHibernateTemplate().update(account);
}
public void deleteAccount(int accountNumber){
Account account=getHibernateTemplate().get(Account.class, accountNumber);
if(account!=null){
getHibernateTemplate().delete(account);
}
}
#SuppressWarnings("unchecked")
public List<Account> getAllAccount()
{
return getHibernateTemplate().find("from Account");
}
}
Account.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.hibernateWithSpring.Account" table="account">
<id name="accountNumber" column="account_number" type="int"></id>
<property name="owner" column="owner" type="string"></property>
<property name="balance" column="balance" type="double"></property>
</class>
</hibernate-mapping>
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="accountDaoBean" class="com.hibernateWithSpring.AccountDao">
<property name="hibernateTemplate" ref="hibernateTemplateBean"></property>
</bean>
<bean id="hibernateTemplateBean" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sfBean"></property>
</bean>
<bean id="sfBean" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceBean"></property>
<property name="mappingResources">
<value>com/hibernateWithSpring/Account.hbm.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/accountdb"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
My db Details are correct But I have no idea why i am getting this error:-
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountDaoBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Cannot resolve reference to bean 'hibernateTemplateBean' while setting bean property 'hibernateTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplateBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Cannot resolve reference to bean 'sfBean' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sfBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
Things you need to fix:
1 - put the JAR (javaee-api) in your LIB folder
http://mvnrepository.com/artifact/javax/javaee-api/7.0
2 - if you are using Maven, add the following dependency
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
3 - Configure your artifact and include this jar, allowing to be deployed
4 - Put the javaee-api jar in your tomcat/jboss lib folder
I am receiving a NullPointerException with the following code and configuration, and I am not sure why. I would appreciate some help in debugging this issue.
File persistence.xml:
<persistence-unit name="adismPersistenceUnit" transaction-type="RESOURCE_LOCAL" >
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.adism.domain.Ad</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/adism" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="" />
</properties>
</persistence-unit>
Entity Class:
#Entity #Table(name = "ads") public class Ad {
private Integer adId;
private String adTitle;
public Ad(){}
#Id
#Column(name="adid")
#GeneratedValue
public Integer getAdId(){
return adId;
}
public void setAdId(Integer adId){
this.adId = adId;
}
#Column(name="adtitle")
public String getAdTitle(){
return this.adTitle;
}
public void setAdTitle(String title){
this.adTitle = title;
}
}
DAO Implementation:
public class AdDaoImpl implements AdDao{
#PersistenceContext
public EntityManager entityManager;
#Override
public void save(Ad ad){
entityManager.persist(ad);
}
}
When I run following code in JSP, I get NullPointerException
Ad ad = new Ad();
ad.setAdId(1000);
ad.setAdTitle("JPA pure");
AdDao newDao = new AdDaoImpl();
newDao.save(ad);
If you just do AdDao newDao = new AdDaoImpl(); your container will not known where to inject the EntityManager.
If you are using JBoss or Glassfish (or someother kind of EJB Containner) you need to declare AdDao as EJB:
#Stateless
public class AdDao () {}
And you will use it in your servlet like:
#EJB
public AdDao ejb;
PS.: I would not inject a DAO in a controller. The best is to use other classes between both, but if you are new to this kind of technology start with it.
If you are using a solution without JPA you can do something like:
private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("YOUR_PERSISTENCE_UNIT"); // store it in your class
public void yourMethod(){
final EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
// do your stuff here
entityManager.getTransaction().commit();
entityManager.close();
}