Jump to content
Sign in to follow this  
soulindo

Erro ao inserir na Base de dados

Recommended Posts

Boas

 

Estou com um erro ao inserir na bd atravez do hibernate eu acho que o erro é porque não tem nenhum session mas não sei se estou correcto se alguem me poder ajudar agradecia.

 

Erro

WARNING: #{testeHibernate.save}: java.lang.NullPointerException
javax.faces.FacesException: #{testeHibernate.save}: java.lang.NullPointerException
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
... 26 more
Caused by: java.lang.NullPointerException
at Impl.UtilizadorDAOimpl.addutilizador(UtilizadorDAOimpl.java:27)
at TesteHibernate.save(TesteHibernate.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 27 more

12345
Ago 29, 2015 7:36:30 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
SEVERE: javax.faces.el.EvaluationException: java.lang.NullPointerException
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at Impl.UtilizadorDAOimpl.addutilizador(UtilizadorDAOimpl.java:27)
at TesteHibernate.save(TesteHibernate.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 27 more

Função save

    public void save() {
        // Calling Business Service
     utiliza.setIdUt(12);
     System.out.println(utiliza.getUser());
     System.out.println(utiliza.getPass());
     System.out.println(utiliza.getTip());

     utdao.addutilizador(utiliza);
    }

Função addutilizador

    private SessionFactory sessionFactory;
    
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    
    public void addutilizador(Utilizador ut) {
Session session = getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        session.persist(ut);
        tx.commit();
        session.close(); 
}

spring.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3307/xp" />
        <property name="username" value="root" />
        <property name="password" value="" />
    </bean>


<!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="SessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>Classhiber.Utilizador</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>


    <bean id="UtilizadorDAOimpl" class="Impl.UtilizadorDAOimpl">
        <property name="sessionFactory" ref="SessionFactory" />
    </bean>
</beans>

Obrigado

Share this post


Link to post
Share on other sites

Bom, se esse SessionFactory vai ser injetado pelo Spring voce poderia tentar fazer isso:

  @Autowired
  private SessionFactory sessionFactory;

ao invés disso

  private SessionFactory sessionFactory;

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • By gabefgonc
      Olá, quando tento fazer um jar com os códigos a seguir, e abro o executável, ele lança a seguinte exceção:
      java.io.FileNotFoundException: res/world/world1.txt (Arquivo ou diretório inexistente)
      at java.base/java.io.FileInputStream.open0(Native Method)
      at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
      at java.base/java.io.FileInputStream.(FileInputStream.java:157)
      at java.base/java.io.FileInputStream.(FileInputStream.java:112)
      at java.base/java.io.FileReader.(FileReader.java:60)
      at br.gabefgonc.javaxswingtests.utils.Utils.loadFileAsString(Utils.java:13)
      at br.gabefgonc.javaxswingtests.worlds.World.loadWorld(World.java:68)
      at br.gabefgonc.javaxswingtests.worlds.World.(World.java:25)
      at br.gabefgonc.javaxswingtests.main.states.GameState.(GameState.java:20)
      at br.gabefgonc.javaxswingtests.main.Game.init(Game.java:95)
      at br.gabefgonc.javaxswingtests.main.Game.run(Game.java:45)
      at java.base/java.lang.Thread.run(Thread.java:834)
      java.lang.NumberFormatException: For input string: “”
      at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
      at java.base/java.lang.Integer.parseInt(Integer.java:662)
      at java.base/java.lang.Integer.parseInt(Integer.java:770)
      at br.gabefgonc.javaxswingtests.utils.Utils.parseInt(Utils.java:26)
      at br.gabefgonc.javaxswingtests.worlds.World.loadWorld(World.java:71)
      at br.gabefgonc.javaxswingtests.worlds.World.(World.java:25)
      at br.gabefgonc.javaxswingtests.main.states.GameState.(GameState.java:20)
      at br.gabefgonc.javaxswingtests.main.Game.init(Game.java:95)
      at br.gabefgonc.javaxswingtests.main.Game.run(Game.java:45)
      at java.base/java.lang.Thread.run(Thread.java:834)
      Exception in thread “Thread-0” java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
      at br.gabefgonc.javaxswingtests.worlds.World.loadWorld(World.java:72)
      at br.gabefgonc.javaxswingtests.worlds.World.(World.java:25)
      at br.gabefgonc.javaxswingtests.main.states.GameState.(GameState.java:20)
      at br.gabefgonc.javaxswingtests.main.Game.init(Game.java:95)
      at br.gabefgonc.javaxswingtests.main.Game.run(Game.java:45)
      at java.base/java.lang.Thread.run(Thread.java:834)
      códigos:
      World.java:
      package br.gabefgonc.javaxswingtests.worlds;
      import br.gabefgonc.javaxswingtests.entities.EntityManager;
      import br.gabefgonc.javaxswingtests.entities.Player;
      import br.gabefgonc.javaxswingtests.entities.Tree;
      import br.gabefgonc.javaxswingtests.inventory.Inventory;
      import br.gabefgonc.javaxswingtests.items.Item;
      import br.gabefgonc.javaxswingtests.items.ItemManager;
      import br.gabefgonc.javaxswingtests.main.Game;
      import br.gabefgonc.javaxswingtests.main.Handler;
      import br.gabefgonc.javaxswingtests.main.tiles.Tile;
      import br.gabefgonc.javaxswingtests.utils.Utils;
      import java.awt.*;
      public class World {
      private int width, height, spawnX,spawnY;
      private int[][] tiles;
      private Handler handler;
      private EntityManager entityManager;
      private ItemManager itemManager;
      public World(Handler handler, String path){
      this.handler = handler;
      entityManager = new EntityManager(handler, new Player(handler, 0, 0));
      loadWorld(path);
      entityManager.getPlayer().setX(spawnX);
      entityManager.getPlayer().setY(spawnY);
      itemManager = new ItemManager(this.handler); } public void tick(){ entityManager.tick(); itemManager.tick(); } public void render(Graphics g){ int xStart = (int) Math.max(0, handler.getCamera().getxOffset() / Tile.TILE_WIDTH); int xEnd = (int) Math.min(width, (handler.getCamera().getxOffset() + handler.getWidth()) / Tile.TILE_WIDTH + 1); int yStart = (int) Math.max(0, handler.getCamera().getyOffset() / Tile.TILE_HEIGHT); int yEnd = (int) Math.min(height, (handler.getCamera().getyOffset() + handler.getHeight()) / Tile.TILE_HEIGHT + 1); for(int y = yStart; y < yEnd; y++){ for(int x = xStart; x < xEnd; x++){ getTile(x, y).render(g, (int) (x * Tile.TILE_WIDTH - handler.getCamera().getxOffset()), (int) (y * Tile.TILE_HEIGHT - handler.getCamera().getyOffset())); } } itemManager.render(g); entityManager.render(g); } public Tile getTile(int x, int y){ Tile t; if(x < width && y < height) t = Tile.tiles[tiles[x][y]]; else t = null; if(t == null){ return Tile.grassTile; } return t; } private void loadWorld(String path){ String file = Utils.loadFileAsString(path); String[] tokens = file.split("\\s+"); System.out.println(tokens[0]); width = Utils.parseInt(tokens[0]); height = Utils.parseInt(tokens[1]); spawnX = Utils.parseInt(tokens[2]); spawnY = Utils.parseInt(tokens[3]); tiles = new int[width][height]; for(int y = 0; y < height; y++){ for(int x = 0; x < width; x++){ tiles[x][y] = Utils.parseInt(tokens[(x + y * width) + 4]); if(Utils.parseInt(tokens[(x + y * width) + 4]) == 5){ entityManager.addEntity(new Tree(handler, x * Tile.TILE_WIDTH, y * Tile.TILE_HEIGHT)); } } } } public int getWidth() { return width; } public int getHeight() { return height; } public EntityManager getEntityManager(){ return entityManager; } public Handler getHandler() { return handler; } public void setHandler(Handler handler) { this.handler = handler; } public ItemManager getItemManager() { return itemManager; } public void setItemManager(ItemManager itemManager) { this.itemManager = itemManager; } }
      Utils.java:
      package br.gabefgonc.javaxswingtests.utils;
      import java.io.BufferedReader;
      import java.io.FileReader;
      import java.io.IOException;
      public class Utils {
      public static String loadFileAsString(String path){ StringBuilder builder = new StringBuilder(); ClassLoader classLoader = ClassLoader.getSystemClassLoader(); try { BufferedReader br = new BufferedReader(new FileReader(path)); String line; while((line = br.readLine()) != null){ builder.append(line + "\n"); } }catch(IOException e){ e.printStackTrace(); } return builder.toString(); } public static int parseInt(String number){ try{ return Integer.parseInt(number); }catch(NumberFormatException e){ e.printStackTrace(); return 0; } } }
      GameState.java:
      package br.gabefgonc.javaxswingtests.main.states;
      import br.gabefgonc.javaxswingtests.entities.EntityManager;
      import br.gabefgonc.javaxswingtests.entities.Player;
      import br.gabefgonc.javaxswingtests.entities.Tree;
      import br.gabefgonc.javaxswingtests.gfx.ImageLoader;
      import br.gabefgonc.javaxswingtests.gfx.SpriteSheet;
      import br.gabefgonc.javaxswingtests.main.Game;
      import br.gabefgonc.javaxswingtests.main.Handler;
      import br.gabefgonc.javaxswingtests.main.tiles.Tile;
      import br.gabefgonc.javaxswingtests.worlds.World;
      import java.awt.*;
      public class GameState extends State {
      private World world;
      public GameState(Handler handler){ super(handler); world = new World(handler, "res/world/world1.txt"); handler.setWorld(world); } public void tick() { world.tick(); } public void render(Graphics g) { world.render(g); } }
      classPath:
      /home/gabriel/Programacao/Games/JavaxSwingTests/res
      Obrigado!
    • By Good
      Boa noite,
       
      estou com dúvidas e estive pensando... se eu fosse criar um sistema de criar lojas virtuais, como poderia ser a estrutura, principalmente nesta parte:
      - um banco de dados para cada loja ou um banco de dados para todas as lojas?
       
      Que seria separado apenas por id de loja, pedidos seriam unicamente visto por cada loja, óbvio...
       
      Qual a sua opinião sobre isto?
    • By gamesmax2
      Pessoal criei um app Webview, com leitor de código de barra, porém tiver que utilizar a Bíblioteca zxing barcode, tá funcionando só que é queria que ao ler o código de barra, no lugar do alert fizesse um redirecionamento com código via get para tá salvando com php no banco de dados.
       
      creio que seja uma função simples um redirecionamento, como tenho conhecimento somente com php, tenho dificuldades com Java do Android.
    • By icaroperetti45
      Faça um programa em JAVA que deve ficar lendo uma letra por vez do teclado até que o operador digite a letra x. Após o operador digitar x o programa deve apresentar na tela o número de vezes que o operador digitou dois caracteres iguais em sequencia.
       
      Rapazeada, sou iniciante no java e gostaria de uma ajuda com o Exercício a seguir! Gostaria de saber como utilizo o != para string no while!
       
      package br.edu.ifcvideira.Lista3;
      import java.util.Scanner;
      public class Exercicio7 {
              public static void main(String[] args) {
                  Scanner in = new Scanner(System.in);
                  
                  String letra = null;
                  String letraCorreta = "x";
                  
                  while (letra.equals(letraCorreta)) {
                      
                  }
              }        
      }
       
    • By gamesmax2
      Pessoal sou  novo com crianção de app android, este app e bastante simples utilizar webview.
      Estou com um problema, queria abrir link externo que não seja do meu site no navegador do celular, meu código abrir todos os links externo no meu app.
       
      exemplo quero que links externo sejam aberto no navegador e link como Youtube ou que utilizar algum app do celular seja aberto nesse app, segue meu codigo:
       
      public class MainActivity extends AppCompatActivity { private WebView cash; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cash = findViewById(R.id.site); cash.getSettings().setJavaScriptEnabled(true); cash.setFocusable(true); cash.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); cash.getSettings().setAppCacheEnabled(true); cash.getSettings().setDomStorageEnabled(true); cash.setWebViewClient(new WebViewClient()); cash.setWebChromeClient(new Meusite()); cash.loadUrl("https://www.meusite.com.br/meu_site/"); } private class Meusite extends WebChromeClient { private View mCustomView; private WebChromeClient.CustomViewCallback mCustomViewCallback; protected FrameLayout mFullscreenContainer; private int mOriginalOrientation; private int mOriginalSystemUiVisibility; Meusite() {} public Bitmap getDefaultVideoPoster() { if (mCustomView == null) { return null; } return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573); } public void onHideCustomView() { ((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView); this.mCustomView = null; getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility); setRequestedOrientation(this.mOriginalOrientation); this.mCustomViewCallback.onCustomViewHidden(); this.mCustomViewCallback = null; } public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback) { if (this.mCustomView != null) { onHideCustomView(); return; } this.mCustomView = paramView; this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility(); this.mOriginalOrientation = getRequestedOrientation(); this.mCustomViewCallback = paramCustomViewCallback; ((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1)); getWindow().getDecorView().setSystemUiVisibility(3846); } } @Override public void onBackPressed() { if (cash.canGoBack()) { cash.goBack(); } else { super.onBackPressed(); } } }  
×

Important Information

Ao usar o fórum, você concorda com nossos Terms of Use.