IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Hibernate Java Discussion :

Problème d'enregistrement dans une base de données


Sujet :

Hibernate Java

  1. #1
    Membre habitué
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    238
    Détails du profil
    Informations personnelles :
    Âge : 36
    Localisation : France, Indre et Loire (Centre)

    Informations forums :
    Inscription : Avril 2009
    Messages : 238
    Points : 183
    Points
    183
    Par défaut Problème d'enregistrement dans une base de données
    Bonjour,

    J'utilise en ce moment une application hibernate/spring et je tente de créer un objet et de l'enregistrer en BDD... mais cela ne marche pas.. aucun message d'erreur mais la BDD reste désespérément vide.. Pourtant lorsque que je tente d'autres requêtes (recherche par ID, test d'existence d'un enregistrement etc...) cela fonctionne parfaitement.

    Voila mes DAO et la définition des beans :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    package com.applira.dao.common.Impl;
     
    import com.applira.dao.common.GenericDao;
     
    import java.io.Serializable;
    import java.lang.reflect.ParameterizedType;
    import java.util.List;
     
    import org.hibernate.Criteria;
    import org.hibernate.LockMode;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.criterion.Criterion;
    import org.hibernate.criterion.Example;
    //import org.springframework.orm.hibernate3.SessionFactoryUtils;
     
    public abstract class GenericDaoImpl<T, ID extends Serializable>
    		implements GenericDao<T, ID> {
     
    	private Class<T> persistentClass;
     
    	private SessionFactory sessionFactory;
     
     
     
     
    	@SuppressWarnings("unchecked")
    	public GenericDaoImpl() {
    		this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
    				.getGenericSuperclass()).getActualTypeArguments()[0];
    	}
     
    	public void setSessionFactory(SessionFactory s) {
    		this.sessionFactory = s;
    	}
     
    	protected Session getSessionFactory() {
    		//boolean allowCreate = true;
            return this.sessionFactory.openSession();
     
    	}
     
    	public Class<T> getPersistentClass() {
    		return persistentClass;
    	}
     
     
    	@SuppressWarnings("unchecked")
    	public T findById(ID id, boolean lock) {
    		T entity;
    		if (lock)
    			entity = (T) getSessionFactory().get(getPersistentClass(), id,
    					LockMode.UPGRADE);
    		else
    			entity = (T) getSessionFactory().get(getPersistentClass(), id);
     
    		return entity;
    	}
     
     
    	public List<T> findAll() {
    		return findByCriteria();
    	}
     
     
    	@SuppressWarnings("unchecked")
    	public List<T> findByExample(T exampleInstance, String... excludeProperty) {
    		Criteria crit = getSessionFactory().createCriteria(getPersistentClass());
    		Example example = Example.create(exampleInstance);
    		for (String exclude : excludeProperty) {
    			example.excludeProperty(exclude);
    		}
    		crit.add(example);
    		return crit.list();
    	}
     
     
    	public T makePersistent(T entity) {
    		getSessionFactory().saveOrUpdate(entity);
    		return entity;
    	}
     
     
    	public void makeTransient(T entity) {
    		getSessionFactory().delete(entity);
    	}
     
     
    	public void flush() {
    		getSessionFactory().flush();
    	}
     
     
    	public void clear() {
    		getSessionFactory().clear();
    	}
     
    	/**
             * Use this inside subclasses as a convenience method.
             */
    	@SuppressWarnings("unchecked")
    	protected List<T> findByCriteria(Criterion... criterion) {
    		Criteria crit = getSessionFactory().createCriteria(getPersistentClass());
    		for (Criterion c : criterion) {
    			crit.add(c);
    		}
    		return crit.list();
    	}
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    /**
     * 
     */
    package com.applira.dao.common.Impl;
     
    import org.hibernate.Criteria;
    import org.hibernate.criterion.Restrictions;
    import org.springframework.dao.DataAccessException;
    import org.apache.log4j.Logger;
    import com.applira.dao.common.UserDao;
    import com.applira.domain.model.User;
     
     
     
     
     
     
    /**
     * @author mcfly
     *
     */
     
    public class UserDaoImpl extends GenericDaoImpl <User, Long> implements UserDao {
     
    	/* (non-Javadoc)
    	 * @see com.applira.dao.common.UserDao#checkLogin(java.lang.String, java.lang.String)
    	 */
    	private static Logger logger = Logger.getLogger(UserDaoImpl.class);
     
     
     
    	public boolean checkLogin(String nomUser, String pwd) {
    		try {
     
    			logger.info("Check user with login: "+nomUser+" and password : [PROTECTED]");
    			Criteria crit = getSessionFactory().createCriteria(User.class);
    			if (nomUser != null){
     
    				crit.add(Restrictions.ilike("nomUser", nomUser));
    			}
    			crit.add(Restrictions.eq("pwd", pwd));
     
    			User user = (User)crit.uniqueResult();
    			return (user != null);
    		}
    		catch(DataAccessException e) {
    			// Critical errors : database unreachable, etc.
    			logger.error("Exception - DataAccessException occurs : "+e.getMessage()
    					+" on complete checkLogin().");
    			return false;
    		}
    	}
     
    	public User findByLogin (String login)
    	{
    		try {
    				Criteria crit = getSessionFactory().createCriteria(User.class);
    				if(login != null) {
    					crit.add(Restrictions.ilike("nomUser", login));
    					User user = (User)crit.uniqueResult();
    					return user;
    				}
    				else {
    					return null;
    				}
    		}
    			catch(DataAccessException e) {
    				logger.error("Exception - dataAccessException occurs : "+e.getMessage()
    						+" on complet findByLogin().");
    			}
    		return null;
     
    	}
     
     
     
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
     
    <!-- Application context DAO layer -->
     
    <beans>
    <!--
    		========================= Start of PERSISTENCE DEFINITIONS =========================
    	-->	
    	<!-- Hibernate sessionFactory definition  -->
    	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    		<property name="configLocation">
    			<value>classpath:hibernate.cfg.xml</value>
    		</property>
    		<property  name="configurationClass">
      			 <value>org.hibernate.cfg.AnnotationConfiguration</value>
    		</property>
    	</bean>
     
    		<!-- Hibernate Transaction Manager Definition -->
    	<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		<property name="sessionFactory" ref="sessionFactory" />
    	</bean>
     
    		<!--
    		========================= Start of DAO DEFINITIONS =========================
    	-->
    		<!-- proxy for DAO using generic DAO -->
    	<bean id="proxyDAO" abstract="true">
    		<property name="sessionFactory" ref="sessionFactory" />
    	</bean>
     
    	<!-- userDao definition -->
    	<bean id="userDao" class="com.applira.dao.common.Impl.UserDaoImpl" parent="proxyDAO"/>
     
    	<!-- instanceDao definition -->
    	<bean id="instanceDao" class="com.applira.dao.common.Impl.InstanceDaoImpl" parent="proxyDAO"/>
     
    	<!--
    	    ========================= Start of SERVICE DEFINITIONS =========================
    	-->
    	<!-- Transactional proxy for Services -->
    	<bean id="proxyService" abstract="true"
    		class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    		<property name="transactionManager" ref="transactionManager" />
    		<property name="transactionAttributes">
    			<props>
    				<prop key="find*">PROPAGATION_REQUIRED, readOnly</prop>
    				<prop key="get*">PROPAGATION_REQUIRED, readOnly</prop>
    				<prop key="*">PROPAGATION_REQUIRED, -java.lang.Exception</prop>
    			</props>
    		</property>
    	</bean>
     
    </beans>
    Et la classe de test :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    package com.applira.common.test;
     
    import static org.junit.Assert.*;
     
    import org.junit.Before;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
     
     
     
    import com.applira.dao.common.UserDao;
    import com.applira.domain.model.User;
     
    public class UserDaoImplTest {
     
     
    	static ApplicationContext context;
     
    	@Before
    	public void setUp() throws Exception {
    		context = new ClassPathXmlApplicationContext("applicationContextDao.xml");
     
    	}
    	@Test
    	public void testCheckLogin() {
     
     
    		UserDao user = (UserDao) context.getBean("userDao");
    		assertTrue(user.checkLogin("pouet", "prout"));
    		assertFalse(user.checkLogin("ab", "ab"));
    	}
     
    	@Test
    	public void testFindByLogin(){
    		UserDao userDao = (UserDao) context.getBean("userDao");
    		User user = userDao.findByLogin("pouet");
    		assertNotNull(user.getNomUser());
     
    	}
     
    	@Test
    	public void testAjoutUser()
    	{
    		UserDao userDao = (UserDao) context.getBean("userDao");
    		User user = new User();
    		user.setNomUser("abc");
    		user.setPwd("abc");
    		user = userDao.makePersistent(user);
    		assertNotNull(userDao.findByLogin("abc"));
    	}
     
    }
    Les deux premiers tests fonctionne parfaitement (j'ai déjà un enregistrement "pouet" prout" en base) Mais lorsque je tente de créer un nouvel user celui-ci n'est pas enregistré en base...

    Et la classe model de User :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    package com.applira.domain.model;
     
    // Generated 6 juil. 2010 10:54:23 by Hibernate Tools 3.2.4.GA
     
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import static javax.persistence.GenerationType.IDENTITY;
    import javax.persistence.Id;
    import javax.persistence.Table;
     
    /**
     * User generated by hbm2java
     */
    @Entity
    @Table(name = "user", catalog = "applira")
    public class User implements java.io.Serializable {
     
    	/**
             * 
             */
    	private static final long serialVersionUID = 1L;
    	private Integer idUser;
    	private String nomUser;
    	private String pwd;
     
    	public User() {
    	}
     
    	public User(String nomUser, String pwd) {
    		this.nomUser = nomUser;
    		this.pwd = pwd;
    	}
     
    	@Id
    	@GeneratedValue(strategy = IDENTITY)
    	@Column(name = "ID_USER", unique = true, nullable = false)
    	public Integer getIdUser() {
    		return this.idUser;
    	}
     
    	public void setIdUser(Integer idUser) {
    		this.idUser = idUser;
    	}
     
    	@Column(name = "NOM_USER", length = 65535)
    	public String getNomUser() {
    		return this.nomUser;
    	}
     
    	public void setNomUser(String nomUser) {
    		this.nomUser = nomUser;
    	}
     
    	@Column(name = "PWD")
    	public String getPwd() {
    		return this.pwd;
    	}
     
    	public void setPwd(String pwd) {
    		this.pwd = pwd;
    	}
     
    }
    Voila, désolé du gros pâté de code mais comme on dit mieux vaut en mettre trops que pas assez

    merci d'avance de vos réponse!!!

  2. #2
    Membre habitué
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    238
    Détails du profil
    Informations personnelles :
    Âge : 36
    Localisation : France, Indre et Loire (Centre)

    Informations forums :
    Inscription : Avril 2009
    Messages : 238
    Points : 183
    Points
    183
    Par défaut
    Bon bah problème résolu, il fallait juste mettre ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    <property name="connection.autocommit">true</property>
    Dans le fichier de configuration d'hibernate, forcèment quand on ne commit pas la donnée n'apparais pas en base

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [MySQL] Enregistrer dans une base de données à partir d'une liste déroulante
    Par snakejl dans le forum PHP & Base de données
    Réponses: 12
    Dernier message: 17/05/2006, 16h32
  2. inscription via le web et enregistrement dans une base de données
    Par titoenis dans le forum Balisage (X)HTML et validation W3C
    Réponses: 11
    Dernier message: 17/05/2006, 09h20
  3. problème d'insertion dans une base de données
    Par belmansour tidjani dans le forum JDBC
    Réponses: 7
    Dernier message: 18/01/2006, 22h13
  4. problème de recherche dans une base de donnée mysql
    Par Xini28 dans le forum SQL Procédural
    Réponses: 3
    Dernier message: 24/10/2005, 18h00
  5. problème de recherche dans une base de données
    Par bouzid_mehdi dans le forum Bases de données
    Réponses: 2
    Dernier message: 19/07/2005, 06h47

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo